简体   繁体   English

如何制作以下元组列表的唯一组合

[英]How to make unique combinations of the following list of tuples

In python, I have a list containing the following tuples: 在python中,我有一个包含以下元组的列表:

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

First tuple contains first names and second tuple contains last names. 第一个tuple包含名字,第二个tuple包含姓氏。
PS: The list I gave is a sample, the actual list varies with more names PS:我给出的列表是一个样本,实际列表随着名称的不同而变化

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. 我怎样才能用Python或任何其他语言实现它。

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. 我试图首先将Bob in tuple 1并与last names in tuple 2组合并执行类似tuple1[1:]以摆脱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. 然后重复(可能的递归?)只有Tom in tuple但我似乎无法围绕算法应该是什么样子。

Any help? 有帮助吗?

You can use itertools.product like this 您可以像这样使用itertools.product

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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