假设我有 names
作为元组列表,其中包含任意顺序的名称元组:
names = [(1,"Alice"), (2,"Bob")]
和genders
作为包含任意顺序的性别元组的另一个元组列表:
genders = [(2,"male"), (1,"female")]
如何通过使用元组的第一个元素作为键来有效匹配两个列表:
result = [("Alice","female"), ("Bob","male")]
最佳答案
简单的一行答案,运行缓慢:
[(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)]
关于python - 在 python 中,如何通过元组元素匹配两个元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657297/