前言:看到一个Excel案例,比如有5个不同的产品,分别为a, b, c, d, e,需要列出所有可能的组合,因为每种产品存在“有”和“没有”2种可能,所以总共就有2的5次方,也就是32种可能;Excel的方法比较复杂,运用到了很多函数和公式,我就想用Python该怎么解决呢?本来想从头设计,但发现原来内置函数itertools里有combinations这个轮子,很简单,短短10行代码就解决了
from itertools import combinations
def combine(temp_list, n):
'''根据n获得列表中的所有可能组合(n个元素为一组)'''
temp_list2 = []
for c in combinations(temp_list, n):
temp_list2.append(c)
return temp_list2
list1 = ['a', 'b', 'c', 'd', 'e', 'f']
end_list = []
for i in range(len(list1)):
end_list.extend(combine(list1, i))
print(end_list)