Python - get all combinations of a list

前端 未结 3 1950
[愿得一人]
[愿得一人] 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:49

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

提交回复
热议问题