如何将这个random.choices python列表转换为字符串?

2024-10-03 13:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python制作一个Discord机器人, 我希望bot使用随机消息进行响应,使用random.choice可以很好地工作 不过,我想补充一点。我发现有random.choices(docshere) 您可以将权重添加到列表中,以便某些权重比其他权重更频繁地拾取。 现在我有:

@bot.event
async def on_member_join(channel):
    time.sleep(2)

    channel = bot.get_channel(723954693826674701)
    brankos_greetings = [
        "testMessageCommon1",
        "testMessageCommon2",
        "testMessageCommon3",
        "testMessageCommon4",
        "testMessageCommon5",
        "testMessageCommon6",
        "testMessageCommon7",
        "testMessageCommon8",
        "testMessageCommon9",
        "testMessageCommon10",

        "testMessageSemiRare1",
        "testMessageSemiRare2",
        "testMessageSemiRare3",
        "testMessageSemiRare4",
        "testMessageSemiRare5",
        "testMessageSemiRare6",
        "testMessageSemiRare7",

        "testMessageRare1",
        "testMessageRare2"
    ]

    weights = [
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,
        0.077,

        0.03,
        0.03,
        0.03,
        0.03,
        0.03,
        0.03,
        0.03,
        
        0.01,
        0.01,
    ]

    response = random.choices(brankos_greetings, weights, k = 1)
    await channel.send(response)

但是,这会在chat:['testMessageCommon1'] ['testMessageRare1']中提供此输出。等

我试过: response = str(random.choices(brankos_greetings, weights, k = 1))

await channel.send(str(response))

response = random.choices(brankos_greetings, weights, k = 1).strip('[]')

await channel.send(response.strip(['']))

但什么都不管用

所以我的问题是:如何将这个列表转换成字符串


Tags: send列表responsebotchannelrandomawaitchoices
3条回答

random.choices()将结果作为列表返回。由于您有k=1,这意味着返回的结果将是一个包含一个元素的列表。要将该元素作为消息发送,您需要索引和访问该元素。换句话说,

response = random.choices(brankos_greetings, weights, k = 1)
await channel.send(response[0]) # index the first (zeroth) element

我想这可能有用 response = " ".join(response)

可以使用join()方法将字符串数组连接在一起

response = ' '.join(random.choices(brankos_greetings, weights, k = 1))

相关问题 更多 >