首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >选择随机xx应答python bot

选择随机xx应答python bot
EN

Stack Overflow用户
提问于 2018-06-06 22:17:36
回答 2查看 1.3K关注 0票数 1

如何让python bot随机选择一个名字。例如,如果我提供一个答案列表。

answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

@bot.command()  
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-06 23:17:04

如果您使用的是random.choices 3.6+,则可以使用Python (而不是choice)选择替换的Python项

@bot.command()  
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")

@choose.error
def choose_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await bot.say("Please specify how many")
票数 2
EN

Stack Overflow用户

发布于 2018-06-06 22:40:11

import random 

answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

def pick5(listOfAnswers):
    print("This is your random 5 pick:")

    for i in range(0, 5):
        myInt = random.randint(0,len(listOfAnswers)-1)
        print(listOfAnswers[myInt])
        listOfAnswers.remove(listOfAnswers[myInt])

pick5(answers)

此Python函数从给定列表中随机选取5个元素。

它迭代5次,并使用随机选择的整数从给定的列表中拉出一个元素,然后将其删除以避免重复。它使用random模块来实现这一点。

我不知道如何让它变得不和谐,但我想这就是你要找的。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50722715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档