python - 获取任意长度列表中每个列表的所有可能组合

标签 python list loops

假设我有一个列表:啤酒

speights = [1, 10]    
tui = [2, 7]    
export = [3, 9]    
beers = [speights, tui, export]

所以我只能找到如何获取列表列表的每种可能的组合,即:(itertools.product(*beers)) 但这给了我每一个组合,包括每种啤酒的评级和指数。

为了更清楚地说明这一点,因为我正在努力解释这个概念:

[[speights], [speights, tui], [speights, export], [speights, tui, export], 
 [tui], [tui, speights], [tui, export], [tui, speights, export]
 ..... etc.]

这是所需的输出,它必须适用于任意长度的列表列表。

如果之前有人提出过任何帮助,我们将不胜感激,并且很抱歉,因为我似乎找不到这个具体问题。

最佳答案

您可以组合permutationschain.from_iterable :

>>> from itertools import permutations, chain
>>> beers = ['speights', 'tui', 'export']
>>> list(chain.from_iterable(permutations(beers, i) for i in xrange(1, len(beers) + 1)))
[('speights',), ('tui',), ('export',), ('speights', 'tui'), ('speights', 'export'), ('tui', 'speights'), ('tui', 'export'), ('export', 'speights'), ('export', 'tui'), ('speights', 'tui', 'export'), ('speights', 'export', 'tui'), ('tui', 'speights', 'export'), ('tui', 'export', 'speights'), ('export', 'speights', 'tui'), ('export', 'tui', 'speights')]

关于python - 获取任意长度列表中每个列表的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267880/

相关文章:

python - 没有找到模块错误 : No module named 'distributed'

python - 负面 list 索引?

python - 加入两个列表以创建一个新列表

PHP 循环遍历 MySQL 函数返回的数组

JavaScript 属性最终会陷入循环

python - MaxPooling2D、Conv2D、UpSampling2D层的输出大小是如何计算的?

python - 在作业文件中加载 virtualenv 以在 linux 集群上运行

c++ - 迭代时删除列表中的最后一个元素会导致错误

list - 有没有办法只对 Prolog 中包含字母和整数的对列表中的整数求和?

performance - Haskell 显式递归与 `iterate`