Python - get all combinations of a list

自古美人都是妖i 提交于 2019-12-09 02:43:53

问题


I know that I can use itertools.permutation to get all permutation of size r. But, for itertools.permutation([1,2,3,4],3) it will return (1,2,3) as well as (1,3,2).

  1. I want to filter those repetitions (i.e obtain combinations)

  2. Is there a simple way to get all permutations (of all lengths)?

  3. How can I convert itertools.permutation() result to a regular list?


回答1:


Use itertools.combinations and a simple loop to get combinations of all size.

combinations return an iterator so you've to pass it to list() to see it's content(or consume it).

>>> from itertools import combinations
>>> lis = [1, 2, 3, 4]
for i in xrange(1, len(lis) + 1):  #  xrange will return the values 1,2,3,4 in this loop
    print list(combinations(lis, i))
...     
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1,2,3,4)]



回答2:


It sounds like you are actually looking for itertools.combinations():

>>> from itertools import combinations
>>> list(combinations([1, 2, 3, 4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

This example also shows how to convert the result to a regular list, just pass it to the built-in list() function.

To get the combinations for each length you can just use a loop like the following:

>>> data = [1, 2, 3, 4]
>>> for i in range(1, len(data)+1):
...     print list(combinations(data, i))
... 
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]

Or to get the result as a nested list you can use a list comprehension:

>>> [list(combinations(data, i)) for i in range(1, len(data)+1)]
[[(1,), (2,), (3,), (4,)], [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)], [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)], [(1, 2, 3, 4)]]

For a flat list instead of nested:

>>> [c for i in range(1, len(data)+1) for c in combinations(data, i)]
[(1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)]



回答3:


You need itertools.combinations(). And to get a regular list, just use list() factory function.

>>> from itertools import combinations
>>> list(combinations([1, 2, 3, 4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]


来源:https://stackoverflow.com/questions/17176887/python-get-all-combinations-of-a-list

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