如何从n个列表中形成所有可能的组合

问题描述 投票:2回答:2

此问题很难在标题中表达,因此需要一个示例:

我有3个列表:

L1 = ["Eagle", "Panther"]

L2 = ["Warrior", "Talon", "Machete"]

L3 = ["Feather", "Raptor", "Hunter", "Piranha"]

列表的大小可以不同。

我想形成all个子集{[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解决方案

此问题很难在标题中表达,因此需要一个示例:我有3个列表:L1 = [“ Eagle”,“ Panther”] L2 = [“ Warrior”,“ Talon”,“ Machete”] L3 = [“羽毛”,“猛禽”,“猎人”,“ ...

python list subset combinations itertools
2个回答
4
投票

itertools.product用于此。


2
投票
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)
© www.soinside.com 2019 - 2024. All rights reserved.