import random
def random_letters():
x = random.randrange(0, 28)
for i in range (1,29):
n = ["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z"]
print (n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x], n[x])
random_letters()
上面是我每次调用 random_letters() 方法时打印随机打乱字母的尝试,尽管它不起作用。我可以使用什么方法来产生这种效果?
最佳答案
您编写的内容不起作用,因为 x = random.randrange(0, 28)
返回单个随机数,当您打印 n[x]
时,它始终将是同一个角色。即使您在 for
循环中声明了 x = random.randrange(0, 28)
,也不足以确保每个字符都不同,因为它会必须在所有循环中生成所有不同的数字,这是极不可能的。
解决方法是创建一个与字符列表长度相同的范围列表,然后使用 random.shuffle
对其进行打乱。并使用打乱列表的索引打印字符列表:
from random import shuffle
def random_letters(length):
n = ["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l", "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z"]
list1 = list(range(len(n)))
shuffle(list1) # Try printing list1 after this step
for i in range(length):
print(n[list1[i]],end="") # The end paramater is here to "concatenate" the characters
>>> random_letters(6)
grmöçd
>>> random_letters(10)
mbzfeıjkgş
关于python - 如何每次给一个变量不同的随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45094263/