在python中如何通过元组元素匹配两个元组列表?

时间:2011-04-14 00:33:23

标签: python list tuples

假设我有names作为包含任意顺序名称元组的元组列表:

names = [(1,"Alice"), (2,"Bob")]

genders作为另一个包含任意顺序的性别元组的元组列表:

genders = [(2,"male"), (1,"female")]

如何通过使用元组的第一个元素作为获取键来有效匹配这两个列表:

result = [("Alice","female"), ("Bob","male")]

2 个答案:

答案 0 :(得分:7)

转换为字典,收集密钥并进行迭代。

答案 1 :(得分:7)

简单的单行答案,运行缓慢:

[(name, gender) for (id0, gender) in genders for (id1, name) in names if id0==id1]

更好的回答(见Ignazio的回答):

namedict = dict(names)
genderdict = dict(genders)
[(namedict[id], genderdict[id]) for id in set(namedict) & set(genderdict)]