简体   繁体   English

使用python获取列表的排列

[英]Get permutations of lists using python

Let's assume I have list a: 假设我列出了:

a = [0, 0, [0, 1], [0, 1, 2]]

where a can be of any length, and its constituents can be of any length and I want to generate a new list that can be any combination of the values such that for the given example I would return: 其中a可以是任何长度,其组成可以是任何长度,我想生成一个新列表,该列表可以是值的任意组合,以便对于给定的示例,我将返回:

b = [[0,0,0,0],
     [0,0,0,1],
     [0,0,0,2], 
     [0,0,1,0],
     [0,0,1,1],
     [0,0,1,2]]

I think it's just a matter of looping, but I would appreciate any help. 我认为这只是循环的问题,但我将不胜感激。

Thanks 谢谢

Using itertools.product : 使用itertools.product

>>> import itertools
>>> a = [0, 0, [0, 1], [0, 1, 2]]
>>> a2 = [x if isinstance(x, list) else [x] for x in a]
>>> #  = [[0], [0], [0, 1], [0, 1, 2]]
>>> list(itertools.product(*a2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 1, 0), (0, 0, 1, 1), (0, 0, 1, 2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM