Python 3.5循环在每次迭代时生成一个新列表

我正在尝试编写一些代码(伪随机地)生成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,1,24]
[15,42,35,54,43,28,14]
etc
guzizai2009 回答:Python 3.5循环在每次迭代时生成一个新列表

如果我正确理解了这个问题,目标是将一个功能重复19次。但是,此功能会在每次调用时缓慢地从列表中删除项目,从而无法超出问题当前所写的池的大小。我怀疑解决方案是这样的:

import random

def spinAndPrune():
    random.shuffle( pool )
    current_choice = random.choice( pool )
    pool.remove( current_choice )
    random.shuffle( pool )
    return current_choice

首先,我在函数调用的末尾添加了一个return命令。接下来,您可以复制原始池,以便可以根据需要将其重新运行多次。另外,您需要存储要保留的列表:

# create an original pool of values
original_pool = list( range( 1,60 ) )

# initialize a variable that stores previous runs
pool_list = []

# repeat 19 times
for i in range( 19 ):

    # create a copy of the original pool to a temporary pool
    pool = original_pool.copy()

    # run seven times,storing the current choice in variable a
    a = [ spinAndPrune() for x in range( 7 ) ]

    # keep track of variable a in the pool_list
    pool_list.append( a )
    print( a )

请注意.copy()函数可复制列表。顺便说一句,range()使创建包含整数1到59的列表变得容易。

如果您需要提取特定列表,则可以按照以下步骤进行操作:

# print first list
print( pool_list[ 0 ] )

# print fifth list
print( pool_list[ 4 ] )

# print all the lists
print( pool_list )
,

在另一个答案中,我通过修改原始问题中的代码来实现。但是,如果重点只是提取X个值而不在集合/列表中重复,则仅使用random.sample()函数可能是最简单的。代码可以是这样的:

import random

pool = list( range( 1,60 ) )
pool_list = []

# sample 19 times and store to the pool_list
for i in range( 19 ):
    sample = random.sample( pool,7 )
    pool_list.append( sample )
    print( sample )
本文链接:https://www.f2er.com/2939910.html

大家都在问