In Python how do I create variable length combinations or permutations?

和自甴很熟 提交于 2021-02-02 06:43:47

问题


Lets say I have an array called arr = [1,2,3,4]

How can I generate all the possible combinations with minimum 2 arguments that end up looking like

[1,2]
[1,3]
[1,4]
[1,2,3]
[1,2,4]
[1,2,3, 4]
[2,3]
[2,4]

and so on and so forth? Nothing Im trying works. I cant seem to use itertools.combinations or permutations because I need to know the argument size and I cant seem to use itertools.products because that will take minimum one argument from each of a list of lists that looks like this [[1],[2],[3],[4],[5]]. Extra thanks for one liners and comprehensions.

If I wanted to add them all together would that be too much to ask in terms of help? ;-)


回答1:


How about:

(x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))

or

[x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]

if you need the list.

This is the equivalent of the following nested loop

res = []
for l in range(2, len(arr)):
    for x in itertools.combinations(arr, l):
        res.append(x)
return res



回答2:


From : http://wiki.python.org/moin/Powerful%20Python%20One-Liners use following to create all subsets and then refine those with length less than 2

f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]

print [k for k in f([1,2,3,4]) if len(k) >1]


来源:https://stackoverflow.com/questions/17686649/in-python-how-do-i-create-variable-length-combinations-or-permutations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!