【问题标题】:How to find all the combinations of list elements without using itertools?如何在不使用 itertools 的情况下找到列表元素的所有组合?
【发布时间】:2019-07-03 20:09:41
【问题描述】:

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

【问题讨论】:

标签: python-3.x


【解决方案1】:

使用递归提供了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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多