Python:从多个列表中随机选择,不重复
假设我有4个列表,每个列表有10个不同的选项,我想从这四个列表中的每一个列表中选择一个项目,用户指定的次数。但没有重复输出。这可能吗?我似乎写不出任何不重复输出的东西。这样的东西应该可以:Python:从多个列表中随机选择,不重复,python,Python,假设我有4个列表,每个列表有10个不同的选项,我想从这四个列表中的每一个列表中选择一个项目,用户指定的次数。但没有重复输出。这可能吗?我似乎写不出任何不重复输出的东西。这样的东西应该可以: population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] population = set(population) samples = random.sample(population, 3) a,b,c,d = initialize_lists() output_pic
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
population = set(population)
samples = random.sample(population, 3)
a,b,c,d = initialize_lists()
output_picked_before = set()
n = number_of_experiments()
for i in range(n):
t = pick_random_combination_from_list(a,b,c,d)
while t in output_picked_before:
t = pick_random_combination_from_list(a,b,c,d)
print t
output_picked_before.add(t)
像这样的方法应该会奏效:
a,b,c,d = initialize_lists()
output_picked_before = set()
n = number_of_experiments()
for i in range(n):
t = pick_random_combination_from_list(a,b,c,d)
while t in output_picked_before:
t = pick_random_combination_from_list(a,b,c,d)
print t
output_picked_before.add(t)
假设我们有以下
4个列表:
>>> lists = [range(10*i, 10*(i+1)) for i in range(4)]
>>> lists
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]]
首先,洗牌:
>>> for lst in lists: random.shuffle(lst)
>>> lists
[[6, 8, 2, 1, 3, 5, 9, 0, 7, 4], [17, 12, 16, 10, 14, 15, 18, 11, 13, 19], [20, 28, 23, 21, 27, 25, 24, 29, 26, 22], [35, 32, 38, 31, 39, 34, 30, 33, 36, 37]]
然后用zip
输出值:
>>> for items in zip(*lists):
print(items)
(6, 17, 20, 35)
(8, 12, 28, 32)
(2, 16, 23, 38)
(1, 10, 21, 31)
(3, 14, 27, 39)
(5, 15, 25, 34)
(9, 18, 24, 30)
(0, 11, 29, 33)
(7, 13, 26, 36)
(4, 19, 22, 37)
如果您只需要指定数量的,只需使用:
假设我们有以下4个列表:
>>> lists = [range(10*i, 10*(i+1)) for i in range(4)]
>>> lists
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]]
首先,洗牌:
>>> for lst in lists: random.shuffle(lst)
>>> lists
[[6, 8, 2, 1, 3, 5, 9, 0, 7, 4], [17, 12, 16, 10, 14, 15, 18, 11, 13, 19], [20, 28, 23, 21, 27, 25, 24, 29, 26, 22], [35, 32, 38, 31, 39, 34, 30, 33, 36, 37]]
然后用zip
输出值:
>>> for items in zip(*lists):
print(items)
(6, 17, 20, 35)
(8, 12, 28, 32)
(2, 16, 23, 38)
(1, 10, 21, 31)
(3, 14, 27, 39)
(5, 15, 25, 34)
(9, 18, 24, 30)
(0, 11, 29, 33)
(7, 13, 26, 36)
(4, 19, 22, 37)
如果您只需要指定数量的,只需使用:
你为什么不能?Python内置了set
s。发布您编写但不起作用的代码。一旦选中某个项目,您能否将其从列表中删除?请举例说明您希望执行的操作。现在还不清楚你想要达到什么目标。你看,为什么不能呢?Python内置了set
s。发布您编写但不起作用的代码。一旦选中某个项目,您能否将其从列表中删除?请举例说明您希望执行的操作。不太清楚你想要达到什么目标。请参见和。