我需要在另一个列表中生成x个唯一列表

问题描述

我能够生成所需的输出,但是我需要10个输出,并且每个列表都必须是唯一的。我想到的最好的解决方案是创建第二个函数生成一个emty列表,并使用第一个函数的列表填充每个元素。到目前为止,我得到的输出是列表数量的x,但是它们不是唯一的,当我尝试调用第二个函数中的第一个函数时,python给了我错误


import random

numbers = list(range(1,35))
out = []
final = []
print(numbers)  # to see all numbers

# returns 7 unique pop'd numbers from list 'numbers' and appends them to list 'out'
def do():
    for x in range(7):
        out.append(numbers.pop(random.randrange(len(numbers))))

    print(sorted(out))


# In other words i want to print output from function do() 10 times but each item in list has to be unique,not the lists themself

def do_ten():
    for x in range(10):
        final.append(out)
        # do()  python doesnt like this call 
    print(sorted(final))


do_ten()

解决方法

这会生成特定数量的列表,列表中包含从1100的随机数,您可以使用ln来控制数量分别是列表和数字。

import random

l,n = 3,5 # The amount of lists and numbers respectively.
lis = [[i for i in random.sample(range(1,35),n)] for group in range(l)]
print(lis)

随机输出:

[[16,11,17,13,9],[26,6,16,29,24],[24,2,4,1,20]]
,

有帮助吗?

num_lists = 10
len_list = 10 

[list(np.random.randint(1,len_list)) for _ in range(num_lists)]

由于某些人对“唯一性”的定义可能不同,因此您可以尝试:

source_list = range(0,num_lists*len_list,1)
[list(np.random.choice(source_list,len_list,replace=False)) for _ in range(num_lists)]
,

您正在从包含34个元素(从1到34)的列表中弹出10次7个数字。这不可能。您的列表numbers中至少需要有70个元素(例如,从0到69)。

根据您已经编写的代码,这是一个可行的解决方案:

import random

numbers = list(range(0,70))
final = []
print(numbers)  # to see all numbers

# returns a list of 7 unique popped numbers from list 'numbers'
def do():
    out = []
    for x in range(7):
        l = len(numbers)
        r = random.randrange(l)
        t = numbers.pop(r)
        out.append(t)
    return out

# Call 10 times do() and add the returned list to 'final'
def do_ten():
    for x in range(10):
        out = do() # Get result from do()
        final.append(out) # Add it to 'final'

do_ten()
print(final)
,

可以使用random.sample从数字范围中抽取34个数字中的7个而无需重复-为了确保您不会得到重复的列表,可以将列表的元组添加到集合中,并最终结果仅添加如果该元组尚未在集合中,则最终确定:

import random

numbers = range(1,35)  # 1...34

final = []
chosen = set()
while len(final) < 10:
    # replace popping numbers with random.sample
    one_list = random.sample(numbers,k=7) # 7 numbers out of 34 - no repeats
    # create a tuple of this list and only add to final if not yet added
    t = tuple(one_list)
    if t not in chosen:
        chosen.add(t)
        final.append(one_list)

print (final)

输出:

[[1,5,10,26,14,33,6],[3,30,7,21,18],23,28,18,1],[4,25,32,15,22,8,27],[32,9,12],[34,20],[6,34,12,5],[29,3,31,15],19,15]]

如果您不需要唯一的结果列表,可以将其简化为单行,但其中可能包含重复项:

final = [random.sample(range(1,11),k=7) for _ in range(10)]