简体   繁体   中英

How to make unique combinations of the following list of tuples

In python, I have a list containing the following tuples:

[(Bob, Tom), (GreenWood, Pearson)]

First tuple contains first names and second tuple contains last names.
PS: The list I gave is a sample, the actual list varies with more names

The thing I am trying to do is generate all the possible names that can be generated ie

- Bob GreenWood
- Bob Pearson
- Tom GreemWood
- Tom Pearson

How can I implement this in Python preferably or any other language.

I trying to first take the Bob in tuple 1 and make combinations with last names in tuple 2 and do something like tuple1[1:] to get rid of the Bob. Then repeat (possible recursion?) with only Tom in tuple but I can't seem to wrap my head around how the algorithm should look like.

Any help?

You can use itertools.product like this

from itertools import product
names = [('Bob', 'Tom'), ('GreenWood', 'Pearson')]
for item in product(*names):
    print(item)

Output

('Bob', 'GreenWood')
('Bob', 'Pearson')
('Tom', 'GreenWood')
('Tom', 'Pearson')

If you wanted to print the possible names as string, then you can join the result like this

print(" ".join(item))

This will produce

Bob GreenWood
Bob Pearson
Tom GreenWood
Tom Pearson

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