python - 如何每次给一个变量不同的随机值?

标签 python python-3.x

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/

相关文章:

Python CLI 进度条/旋转器,无需迭代

python - 如何在 pymongo 的 find_one_and_update() 方法中查询多个过滤器?

python - Luhn 公式不适用于不同的输入

python - XGBoost 在 Windows 中的安装

python-3.x - 使用tornado.ioloop.IOLoop.run_in_executor时如何避免线程过多?

python-3.x - 当函数返回特定类型的对象或 None 时,指定什么类型提示?

python - 如何使用列表列表的特定部分的统计信息

python - 解析位置 8 处的日期时间字符串 "09-11-2017 00:02:00"时出错

python - 在 EC2 上运行 mapreduce 作业时如何获取文件名?

python - 如何在windows后台运行python脚本?