Python-获取列表的所有组合 [英] Python - get all combinations of a list

查看:95
本文介绍了Python-获取列表的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用itertools.permutation获得大小为r的所有排列. 但是,对于itertools.permutation([1,2,3,4],3),它将返回(1,2,3)(1,3,2).

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. 我想过滤掉这些重复(即获得组合)

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

是否有一种简单的方法来获取所有长度的所有排列?

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

如何将itertools.permutation()结果转换为常规列表?

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

推荐答案

使用 itertools.combinations 和一个简单的循环即可获得所有大小的组合.

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

combinations返回一个迭代器,因此您必须将其传递给list()才能查看其内容(或使用它).

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

这篇关于Python-获取列表的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆