简体   繁体   中英

How can I form all possible combinations from n lists

This question is difficult to word in the title, so an example is required:

I have 3 lists:

L1 = ["Eagle", "Panther"]

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

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

The lists can be of different sizes.

I want to form all subsets {[a,b,c]} such that a is in L1 , b in L2 , c in L3

An example is as follows:

{["Eagle", "Warrior", "Feather"], ["Eagle", "Warrior", "Raptor"], ["Panther", "Machete", "Feather"]...}

["Eagle", "Warrior", "Feather"] is the same as ["Eagle", "Feather", "Warrior"] , so order does not matter.

I just need all the subsets.

I saw many posts where I can form a subset of a list, but couldn't find what I am looking for here. I can obviously loop and do it, but was wondering if there is an itertools solution

itertools.product is used for this.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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