Python 获取任意长度列表中每个列表的所有可能组合
假设我有一个列表:Python 获取任意长度列表中每个列表的所有可能组合,python,list,loops,Python,List,Loops,假设我有一个列表:啤酒 speights = [1, 10] tui = [2, 7] export = [3, 9] beers = [speights, tui, export] 因此,我只能找到如何获得列表的所有可能组合,即:(itertools.product(*beers)) 但这给了我每种组合,包括每种啤酒的评级和指数 为了更清楚地说明这一点,我正在努力解释这一概念: [[speights], [speights, tui], [speights, expo
啤酒
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.]
这是所需的输出,它必须处理任意长度的列表
如果以前有人问过我,我将不胜感激和抱歉,因为我似乎找不到这个特定的问题。您正在寻找任何长度的
排列。试试这个:
import itertools
...
c = []
for i in range(len(beers)):
c.extend(itertools.permutations(beers, i + 1))
print(c)
将屈服
[([1, 10],), ([2, 7],), ([3, 9],), ([1, 10], [2, 7]), ([1, 10], [3, 9]),
([2, 7], [1, 10]), ([2, 7], [3, 9]), ([3, 9], [1, 10]), ([3, 9], [2, 7]),
([1, 10], [2, 7], [3, 9]), ([1, 10], [3, 9], [2, 7]), ([2, 7], [1, 10], [3, 9]),
([2, 7], [3, 9], [1, 10]), ([3, 9], [1, 10], [2, 7]), ([3, 9], [2, 7], [1, 10])]
您可以结合:
这就是所谓的动力集。这可能会帮助您寻找解决方案。谢谢,这非常有效!只是想知道有没有办法让它拥有多重自我?所以一个列表可以是(tui,tui,speights),(tui,tui,tui)等等?@blueden:你可以通过调用product(beers,repeat=i)
而不是permutations(beers,i)
,详情请参见。
>>> 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')]