如何在不使用itertools的情况下找到列表元素的所有组合?

时间:2019-07-03 12:06:46

标签: python-3.x

我正在寻找一种无需使用itertools就能找到列表元素所有可能组合的算法。 例如。 :对于[1,2,3,4,5],它打印[[1],[2],[3],[4],[5],[1,2],[1,3],[1 ,4],[1,5],[2,1] .......]

1 个答案:

答案 0 :(得分:0)

使用递归here提出了一个解决方案。

>>> import copy
>>> def combinations(target,data):
...     for i in range(len(data)):
...         new_target = copy.copy(target)
...         new_data = copy.copy(data)
...         new_target.append(data[i])
...         new_data = data[i+1:]
...         print new_target
...         combinations(new_target,
...                      new_data)
...                      
... 
>>> target = []
>>> data = ['a','b','c','d']
>>> 
>>> combinations(target,data)
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'd']
['a', 'c']
['a', 'c', 'd']
['a', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['b', 'd']
['c']
['c', 'd']
['d']