2013-12-13 30 views
-4

要在python中生成3個(或更多)數字的所有排列,可以使用itertools.permutations。 如何以兩個批次生成組合。從3個數字生成所有組合

例如, :[1, 2, 3] 和輸出:[1,2], [2,3], [1,3]

+2

'itertools.combinations(L1,2)' – roippi

+0

我不知道爲什麼即時獲得負面投票,在SO之前沒有像這樣的任何問題... –

+0

@AbhishekThakur - 我不認爲人們因爲這是一個騙局(事實上,我認爲擬議的欺騙並不是一件好事)。投訴愚蠢是違反本網站的精神。相反,我認爲你因爲沒有足夠的努力來解決問題而陷入低潮。雖然我個人通常會爲此投票結束這個問題,但有些人認爲這個問題更嚴重,並且會降低。或者他們沒有足夠的聲望投票結束這個問題。 – iCodez

回答

8

使用itertools.combinations:號碼的輸入列表

>>> from itertools import combinations 
>>> lst = [1, 2, 3] 
>>> list(combinations(lst, 2)) 
[(1, 2), (1, 3), (2, 3)] 
>>> [list(x) for x in combinations(lst, 2)] 
[[1, 2], [1, 3], [2, 3]] 
>>> 
0
itertools.combinations(iterable, r) 

實施例:

for x in itertools.combinations([1,2,3],2): 
    print x