猿问

列表的所有组合

列表的所有组合

我基本上是在找一个python版本的合二为一List<List<int>>

给定一个列表,我需要一个新的列表,给出列表之间所有可能的项目组合。

[[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,[3,6,10]]

列表的数量是未知的,所以我需要一些对所有情况都有效的东西。优雅加分!


RISEBY
浏览 678回答 3
3回答

慕标5832272

你需要itertools.product:>>> import itertools>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]>>> list(itertools.product(*a))[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

qq_笑_17

最优雅的解决方案是使用itertools.积在python 2.6中。如果您不使用Python2.6,则itertools.Products的docs实际上显示了一个等效的函数来以“手动”的方式完成该产品:def&nbsp;product(*args,&nbsp;**kwds): &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;product('ABCD',&nbsp;'xy')&nbsp;-->&nbsp;Ax&nbsp;Ay&nbsp;Bx&nbsp;By&nbsp;Cx&nbsp;Cy&nbsp;Dx&nbsp;Dy &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;product(range(2),&nbsp;repeat=3)&nbsp;-->&nbsp;000&nbsp;001&nbsp;010&nbsp;011&nbsp;100&nbsp;101&nbsp;110&nbsp;111 &nbsp;&nbsp;&nbsp;&nbsp;pools&nbsp;=&nbsp;map(tuple,&nbsp;args)&nbsp;*&nbsp;kwds.get('repeat',&nbsp;1) &nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;[[]] &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;pool&nbsp;in&nbsp;pools: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result&nbsp;=&nbsp;[x+[y]&nbsp;for&nbsp;x&nbsp;in&nbsp;result&nbsp;for&nbsp;y&nbsp;in&nbsp;pool] &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;prod&nbsp;in&nbsp;result: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;yield&nbsp;tuple(prod)

30秒到达战场

listOLists&nbsp;=&nbsp;[[1,2,3],[4,5,6],[7,8,9,10]]for&nbsp;list&nbsp;in&nbsp;itertools.product(*listOLists): &nbsp;&nbsp;print&nbsp;list;我希望你能像我第一次遇到它时那样优雅。
随时随地看视频慕课网APP

相关分类

Python
我要回答