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