[英]How can I find all the possible combinations of a list of lists (in Python)?
[英]How can I form all possible combinations from n lists
这个问题很难在标题中用词,所以需要一个例子:
我有 3 个列表:
L1 = ["Eagle", "Panther"]
L2 = ["Warrior", "Talon", "Machete"]
L3 = ["Feather", "Raptor", "Hunter", "Piranha"]
列表可以有不同的大小。
我想形成所有子集{[a,b,c]}
使得a
在L1
中, b
在L2
中, c
在L3
一个例子如下:
{["Eagle", "Warrior", "Feather"], ["Eagle", "Warrior", "Raptor"], ["Panther", "Machete", "Feather"]...}
["Eagle", "Warrior", "Feather"]
与["Eagle", "Feather", "Warrior"]
相同,所以顺序无关紧要。
我只需要所有的子集。
我看到了很多帖子,我可以在其中形成列表的子集,但在这里找不到我要查找的内容。 我显然可以循环并做到这一点,但想知道是否有itertools
解决方案
import itertools
L1 = ["Eagle", "Panther"]
L2 = ["Warrior", "Talon", "Machete"]
L3 = ["Feather", "Raptor", "Hunter", "Piranha"]
for x in itertools.product(L1,L2,L3):
print(x)
Output
('Eagle', 'Warrior', 'Feather')
('Eagle', 'Warrior', 'Raptor')
('Eagle', 'Warrior', 'Hunter')
('Eagle', 'Warrior', 'Piranha')
('Eagle', 'Talon', 'Feather')
('Eagle', 'Talon', 'Raptor')
('Eagle', 'Talon', 'Hunter')
('Eagle', 'Talon', 'Piranha')
('Eagle', 'Machete', 'Feather')
('Eagle', 'Machete', 'Raptor')
('Eagle', 'Machete', 'Hunter')
('Eagle', 'Machete', 'Piranha')
('Panther', 'Warrior', 'Feather')
('Panther', 'Warrior', 'Raptor')
('Panther', 'Warrior', 'Hunter')
('Panther', 'Warrior', 'Piranha')
('Panther', 'Talon', 'Feather')
('Panther', 'Talon', 'Raptor')
('Panther', 'Talon', 'Hunter')
('Panther', 'Talon', 'Piranha')
('Panther', 'Machete', 'Feather')
('Panther', 'Machete', 'Raptor')
('Panther', 'Machete', 'Hunter')
('Panther', 'Machete', 'Piranha')
import itertools
L1=["Eagle","Panter"]
L2=["Warrior","Talon","Machete"]
L3=["Feather","Raptor","Hunter","Piranha"]
res=set()
for i in itertools.product(L1,L2,L3):
res.add(tuple(sorted(i)))
print(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.