前言:比如有5个不同的产品,分别为a, b, c, d, e,需要列出所有可能的组合,因为每种产品存在“有”和“没有”2种可能,所以总共就有2的5次方,也就是32种可能;
如何用Python进行枚举呢?
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']
end_list = []
for i in range(len(list1)+1):
end_list.extend(combine(list1, i))
print(end_list)
print(len(end_list))
[(), (‘a’,), (‘b’,), (‘c’,), (‘d’,), (‘e’,), (‘a’, ‘b’), (‘a’, ‘c’),
(‘a’, ‘d’), (‘a’, ‘e’), (‘b’, ‘c’), (‘b’, ‘d’), (‘b’, ‘e’), (‘c’,
‘d’), (‘c’, ‘e’), (‘d’, ‘e’), (‘a’, ‘b’, ‘c’), (‘a’, ‘b’, ‘d’), (‘a’,
‘b’, ‘e’), (‘a’, ‘c’, ‘d’), (‘a’, ‘c’, ‘e’), (‘a’, ‘d’, ‘e’), (‘b’,
‘c’, ‘d’), (‘b’, ‘c’, ‘e’), (‘b’, ‘d’, ‘e’), (‘c’, ‘d’, ‘e’), (‘a’,
‘b’, ‘c’, ‘d’), (‘a’, ‘b’, ‘c’, ‘e’), (‘a’, ‘b’, ‘d’, ‘e’), (‘a’, ‘c’,
‘d’, ‘e’), (‘b’, ‘c’, ‘d’, ‘e’), (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)]
32
原文链接:Link
加油!
感谢!
努力!