问题
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