[英]find 2^n -2 combinations of elements in a list
我有以下清單:
list1 = ['g1','g2','g3','g4']
我想找到2^n-2
組合,其中n
是列表中項目的總數。 對於n = 4
,結果應為2^4 -2 = 14
,即14個組合。
組合為:
[[['g1'],['g2','g3','g4']],[['g2'],['g1','g3','g4']], [['g3'],['g1','g2','g4']],['g4'],['g1','g2','g3']],[['g1','g2'],['g3','g4']],[['g1','g3'],['g2','g4']],[['g1','g4'],['g3','g4']],[['g2','g3'],['g1','g4']],
[['g2','g4'],['g1','g3']],[['g3','g4'],['g1','g2']],[['g1','g2','g3'],['g4']],[['g2','g3','g4'],['g1']],[['g3','g4','g1'],['g2']],[['g4','g1','g2'],['g3']]]
我知道一種方法:在第一次迭代中,將單個元素放入列表,然后將其放入第二個列表中的其他元素: ['g1'],['g2','g3','g4']
在第二次迭代中使用2個元素一個列表和第二個列表中的其他元素。 ['g1','g2'],['g1','g4']
還有其他方法嗎? 我正在用python編寫此程序。 我的方法很昂貴。 是否有任何庫方法可以快速執行此操作。
這是使用itertools
的功能方法
import itertools as iter
list1 = ['g1', 'g2', 'g3', 'g4']
combinations = [iter.combinations(list1, n) for n in range(1, len(list1))]
flat_combinations = iter.chain.from_iterable(combinations)
result = map(lambda x: [list(x), list(set(list1) - set(x))], flat_combinations)
# [[['g1'], ['g4', 'g3', 'g2']], [['g2'], ['g4', 'g3', 'g1']], [['g3'], ['g4', 'g2', 'g1']],...
len(result)
# 14
itertools.combinations(iterable,r)
從可迭代的輸入中返回元素的r長度子序列。 組合按字典順序排序。 因此,如果對輸入的iterable進行排序,則將按排序順序生成組合元組。
from itertools import combinations
list1 = ['g1','g2','g3','g4']
for n in range(1,len(list1)):
for i in combinations(list1,n):
print(set(i), set(list1) - set(i))
出:
{'g1'} {'g2', 'g3', 'g4'}
{'g2'} {'g1', 'g3', 'g4'}
{'g3'} {'g1', 'g2', 'g4'}
{'g4'} {'g1', 'g2', 'g3'}
{'g1', 'g2'} {'g3', 'g4'}
{'g1', 'g3'} {'g2', 'g4'}
{'g1', 'g4'} {'g2', 'g3'}
{'g2', 'g3'} {'g1', 'g4'}
{'g2', 'g4'} {'g1', 'g3'}
{'g3', 'g4'} {'g1', 'g2'}
{'g1', 'g2', 'g3'} {'g4'}
{'g1', 'g2', 'g4'} {'g3'}
{'g1', 'g3', 'g4'} {'g2'}
{'g2', 'g3', 'g4'} {'g1'}
你可以試試這個
我喜歡中文編碼器的解決方案(我想)。 這是我自己的解決方案:
import itertools
def flatten(*z):
return z
list1 = ['g1','g2','g3','g4']
sublists = []
for i in range(1, len(list1)):
sublists.extend(itertools.combinations(list1, i))
pairs = []
for a, b in itertools.product(sublists, sublists):
if len(a) + len(b) == len(list1) and \
len(set(flatten(*a, *b))) == len(list1):
pairs.append((a, b))
print(pairs, len(pairs))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.