随机变量discord.py的随机输出

2024-09-29 23:24:31 发布

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

以下是当前代码:

@client.command()
async def randousername(ctx):
    Letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    Numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

    randomLetter = random.choice(Letters)
    randomNumber = random.choice(Numbers)
    RandomRandom = random.choice('RandomLetter', 'RandomNumber')
    print(RandomRandom, RandomRandom)

现在我要解释我想用它做什么:

我试图随机输出数字和字母。为了使其完全随机,我想使randomNumberrandomLetter在输出中的位置也是随机的

另一种解释是: 假设我print(randomNumber,randomLetter),这个打印了“2o”。代码将永远无法打印“o2”,因为random number放在random letter之前

我怎样才能做到这一点?


Tags: 代码clientasyncdefrandomcommandctxprint
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:31

最简单的方法是将randomly selected个字符存储在一个列表中,shuffle它和join它存储在一个字符串中

from string import ascii_lowercase, digits
from random import choice, shuffle

tmp = [choice(ascii_lowercase), choice(digits)]
shuffle(tmp)
result = "".join(tmp)

如果您喜欢更紧凑的解决方案,这里有一条:

from string import ascii_lowercase, digits
from random import choice, sample

result = "".join(sample(choice(ascii_lowercase) + choice(digits), k=2))

相关问题 更多 >

    热门问题