在列表中找到2 ^ n -2个元素的组合 [英] find 2^n -2 combinations of elements in a list

查看:105
本文介绍了在列表中找到2 ^ n -2个元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表:

list1 = ['g1','g2','g3','g4']

我想找到2^n-2组合,其中n是列表中的项目总数.对于n = 4,结果应为2^4 -2 = 14,即14个组合.

I want to find 2^n-2 combinations where n is the total number of items in the list. For n = 4 the result should be 2^4 -2 = 14, i.e. 14 combinations.

组合为:

[[['g1'],['g2','g3','g4']],[['g2'],['g1','g3','g4']], [['g3'],['g1','g2','g4']],['g4'],['g1','g2','g3']],[['g1','g2'],['g3','g4']],[['g1','g3'],['g2','g4']],[['g1','g4'],['g3','g4']],[['g2','g3'],['g1','g4']],
[['g2','g4'],['g1','g3']],[['g3','g4'],['g1','g2']],[['g1','g2','g3'],['g4']],[['g2','g3','g4'],['g1']],[['g3','g4','g1'],['g2']],[['g4','g1','g2'],['g3']]]

我知道一种方法: 在第一次迭代中,将单个元素放入一个列表,然后将其放入第二个列表中的其他元素:['g1'],['g2','g3','g4'] 在第二次迭代中,将2个元素包含在一个列表中,并将其他元素包含在第二个列表中. ['g1','g2'],['g1','g4'] 还有其他方法吗? 我正在用python编写此程序. 我的方法很昂贵.是否有任何库方法可以快速执行此操作.

I know one approach: in first iteration take single element and put it into a list and other elements in second list: ['g1'],['g2','g3','g4'] in second iteration take 2 elements in a list and other elements in second list. ['g1','g2'],['g1','g4'] Is there any other approach ?? I'm writing this program in python. My approach is costly. Is there any library method to do this quickly.

推荐答案

以下是使用itertools

import itertools as iter

list1 = ['g1', 'g2', 'g3', 'g4']
combinations = [iter.combinations(list1, n) for n in range(1, len(list1))]
flat_combinations = iter.chain.from_iterable(combinations)
result = map(lambda x: [list(x), list(set(list1) - set(x))], flat_combinations)
# [[['g1'], ['g4', 'g3', 'g2']], [['g2'], ['g4', 'g3', 'g1']], [['g3'], ['g4', 'g2', 'g1']],...
len(result)
# 14

这篇关于在列表中找到2 ^ n -2个元素的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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