Python - get all combinations of a list

前端 未结 3 1947
[愿得一人]
[愿得一人] 2021-01-11 12:44

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 13:50

    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)]
    

提交回复
热议问题