假设我有一个列表:啤酒
。
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.]
这是所需的输出,它必须适用于任意长度的列表列表。
如果之前有人提出过任何帮助,我们将不胜感激,并且很抱歉,因为我似乎找不到这个具体问题。
最佳答案
您可以组合permutations
与 chain.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/