Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make unique combinations of the following list of tuples

Tags:

python

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 i.e

- 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?

like image 763
Krimson Avatar asked Dec 02 '25 10:12

Krimson


1 Answers

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
like image 133
thefourtheye Avatar answered Dec 04 '25 01:12

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!