制作列表的所有可能组合 [英] Making all possible combinations of a list

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

问题描述

我需要能够创建一个包含输入列表的所有可能组合的列表. 例如,列表[1,2,3]应该返回[1 [1,2] [1,3] 2 [2,3] 3 [1,2,3]] 列表不必按任何特定顺序排列.在该站点上,我发现了许多使用itertools的函数,但是当我只需要list时,这些函数就会返回对象.

I need to be able to make a list that contains all possible combinations of an inputted list. For example the list [1,2,3] should return [1 [1,2] [1,3] 2 [2,3] 3 [1,2,3]] The list doesn't have to be in any particular order. On this site I've found lots of functions using the itertools but those are returning objects when I need just a list.

推荐答案

只需使用

Simply use itertools.combinations. For example:

import itertools

lst = [1, 2, 3]
combs = []

for i in xrange(1, len(lst)+1):
    combs.append(i)
    els = [list(x) for x in itertools.combinations(lst, i)]
    combs.append(els)

现在combs保留以下值:

[1, [[1], [2], [3]], 2, [[1, 2], [1, 3], [2, 3]], 3, [[1, 2, 3]]]

是的,它与您提供的示例输出略有不同,但是在该输出中,您并未列出所有可能的组合.

Yes, it's slightly different from the sample output you provided, but in that output you weren't listing all possible combinations.

我要在每种尺寸的实际列表之前 列出组合的尺寸,如果您需要的只是组合(不带尺寸,如示例输出中所示),然后尝试这些其他版本的代码:

I'm listing the size of the combination before the actual list for each size, if what you need is simply the combinations (without the size, as it appears in your sample output) then try these other version of the code:

import itertools

lst = [1, 2, 3]
combs = []

for i in xrange(1, len(lst)+1):
    els = [list(x) for x in itertools.combinations(lst, i)]
    combs.extend(els)

现在combs保留以下值:

[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

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

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