我有以下列表:
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编写这个程序。
我的方法很昂贵。是否有任何库方法可以快速完成。
答案 0 :(得分:3)
这是使用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
答案 1 :(得分:2)
itertools.combinations(iterable,r)
从输入iterable返回元素的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'}
你可以试试这个
答案 2 :(得分:0)
我喜欢中国编码员的解决方案(我猜)。这是我自己的解决方案:
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))