2017-04-16 87 views
1

我正在做一個基於組合的問題,只是卡在它。是的,我在Python中並不擅長。Python itertools組合自定義

使用ncr的itertools組合函數僅返回n個可能的組合。我想要一些能夠返回所選擇的r個可能組合的元素,以及其他來自n個未在該迭代中被選中的元素的剩餘元素。

實施例:

>>>from itertools import combinations 
>>>list = [1, 2, 3, 4, 5] 
>>>rslt = combinations(list, 2) 

當選擇[2, 4]它也應該返回[1, 3, 5] 所以應該提前返回像[[2, 4], [1, 3, 5]]

由於

回答

1

itertools.combinations

懲戒從輸入迭代中得到元素的長度子序列。

您可以使用列表理解來獲得其他項目[j for j in l if j not in i]

from itertools import combinations 

l = [1, 2, 3, 4, 5] 

for i in combinations(l,2): 
    print(list(i),[j for j in l if j not in i]) 

,你會得到:

[1, 2] [3, 4, 5] 
[1, 3] [2, 4, 5] 
[1, 4] [2, 3, 5] 
[1, 5] [2, 3, 4] 
[2, 3] [1, 4, 5] 
[2, 4] [1, 3, 5] 
[2, 5] [1, 3, 4] 
[3, 4] [1, 2, 5] 
[3, 5] [1, 2, 4] 
[4, 5] [1, 2, 3] 

順便說一句,它不建議使用list作爲變量名稱。

+0

這是否可以在單行列表理解中完成? – Arman

+1

@Arman'[(list(i),[j for j in l if j not in i])for i in combinations(l,2)]' – McGrady

+0

謝謝,請記住不要用它作爲變量名 – minhaj

1

最簡單的方法是使原始列表的副本,刪除那些在組合中的元素:

from itertools import combinations 
def combinations_and_remaining(l, n): 
    for c in combinations(l, n): 
     diff = [i for i in l if i not in c] 
     yield c, diff 

for i in combinations_and_remaining([1, 2, 3, 4, 5], 2): 
    print(i) 

將輸出

((1, 2), [3, 4, 5]) 
((1, 3), [2, 4, 5]) 
((1, 4), [2, 3, 5]) 
((1, 5), [2, 3, 4]) 
((2, 3), [1, 4, 5]) 
((2, 4), [1, 3, 5]) 
((2, 5), [1, 3, 4]) 
((3, 4), [1, 2, 5]) 
((3, 5), [1, 2, 4]) 
((4, 5), [1, 2, 3]) 

(該組合返回元組;剩餘元素返回列表效率)

0

一個稍微奢侈但有趣的方式將使用combinations兩次:

from itertools import combinations 
n = 5 
k = 2 
lst = list(range(1, n+1)) 
rslt = zip(combinations(lst, k), map(tuple, reversed(list(combinations(lst, n-k))))) 
print(list(rslt)) 
# -> [((1, 2), (3, 4, 5)), ((1, 3), (2, 4, 5)), ((1, 4), (2, 3, 5)), 
#  ((1, 5), (2, 3, 4)), ((2, 3), (1, 4, 5)), ((2, 4), (1, 3, 5)), 
#  ((2, 5), (1, 3, 4)), ((3, 4), (1, 2, 5)), ((3, 5), (1, 2, 4)), 
#  ((4, 5), (1, 2, 3))]