【发布时间】:2020-04-05 00:31:37
【问题描述】:
我正在尝试编写一些代码(伪随机)生成 7 个数字的列表。我让它运行一次。我希望能够循环此代码以生成多个列表,我可以将其输出到 txt 文件(我不需要帮助,我很喜欢使用 i/o 和文件 :)
我现在正在使用这段代码(感谢 Jason 到目前为止):
import random
pool = []
original_pool = list( range( 1,60))
def selectAndPrune(x):
pool = []
list1 = []
random.shuffle(pool)
pool = original_pool.copy()
current_choice = random.choice(pool)
list1.append(current_choice)
pool.remove(current_choice)
random.shuffle(pool)
print(list1)
def repeater():
for i in range(19):
pool_list = []
pool = original_pool.copy()
a = [ selectAndPrune(pool) for x in range(7)]
pool_list.append(a)
repeater()
这给出了单值列表的输出,例如:
[21]
[1]
[54]
[48]
[4]
[32]
[15]
etc.
我想要的输出是 19 个列表,全部包含 7 个随机整数:
[1,4,17,23,45,51,3]
[10,2,9,38,4,1,24]
[15,42,35,54,43,28,14]
etc
【问题讨论】:
-
您正在尝试创建 19 个子列表,每个子列表的长度为 7(总共 133 个元素)。但是每次迭代你都会从池中删除一个元素(在开始时 59 个元素),所以这就是你得到错误的原因。
-
是的。如果您将范围更改为 (2),则代码会附加相同的列表,而不是生成包含 7 个数字的新列表。我想在每次通过时创建一个新列表,并重置池(现在你已经提到了!)
标签: list loops random python-3.5