2013-04-28 91 views
-2

所以說我有4個列表,每個列表中有10個不同的選項,我想從四個列表的每一箇中選擇一個用戶指定的次數。但沒有重複的輸出。這可能嗎?我似乎無法寫出任何不會重複輸出的內容。Python:從多個列表中隨機選擇,無重複

+1

你爲什麼不能呢? Python內置了'set's。 – squiguy 2013-04-28 19:34:37

+1

發佈您編寫但沒有用的代碼。 – 2013-04-28 19:34:42

+1

一旦挑選物品,你可以從清單中刪除物品嗎? – alexn 2013-04-28 19:35:19

回答

2

讓我們假設我們有這些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]] 

而且然後輸出該值s的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) 

如果你只需要其中的規定量,只要使用islice

>>> from itertools import islice 
>>> for items in islice(zip(*lists),5): 
    print(items) 


(6, 17, 20, 35) 
(8, 12, 28, 32) 
(2, 16, 23, 38) 
(1, 10, 21, 31) 
(3, 14, 27, 39) 
1
population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] 
population = set(population) 
samples = random.sample(population, 3) 
0

像這樣的東西應該工作:

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)