2017-05-24 126 views
0

我有三個值的列表(數字和字母),我想寫一個程序,使每個列表之一的隨機組合。蟒蛇使兩個列表中的值的隨機組合

我發現了一個代碼,它可以做出所有可能的值組合,我認爲這可能是一個很好的基礎,但現在我不知道如何繼續。誰能幫我?

下面的代碼我有

import itertools 

square = [a, s, d, f, g, h, j, k, l ] 
circle = [w, e, r, t, z, u, i, o, p ] 
line = [y, x, c, v, b, n, m ] 
radiusshape = [1, 2, 3, 4, 5, 6, 7, 8, 9 ] 

for L in range(0, len(stuff)+1): 
    for subset in itertools.combinations(stuff, L): 
    print(subset) 
+0

你能寫出願望輸出嗎?你需要哪種組合對作爲輸出。單個/多個來自兩個列表或全部,列表內或任何列表。請指定 – Gahan

+0

我希望組合包含每個列表的一個值。例如「awy1」或「stb8」 – malina

+0

那麼你已經從@Martin Broadhurst得到解決方案 – Gahan

回答

0

可以使用random.choice()函數來選擇一個隨機元素從列表中,所以只需使用它的所有4個列表:

from random import choice 

combination = (choice(square), choice(circle), choice(line), choice(radiusshape)) 
+0

太棒了!有用。有什麼辦法可以讓我一次完成X組合? – malina

+1

只需在range()'上使用'for'循環,但我認爲CoryKramer的解決方案更好。 –

3

您可以使用random.sample從畫k隨機樣本的產生cartesian product

# where k is number of samples to generate 
samples = random.sample(itertools.product(square, circle, line, radiusshape), k) 

例如

>>> a = [1, 2, 3, 4] 
>>> b = ['a', 'b', 'c', 'd'] 
>>> c = ['foo', 'bar'] 
>>> random.sample(set(itertools.product(a,b,c)), 5) 
[(1, 'c', 'foo'), 
(4, 'c', 'bar'), 
(1, 'd', 'bar'), 
(2, 'a', 'foo'), 
(2, 'd', 'foo')]