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

标签 python list tuples

假设我有 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/

相关文章:

tuples - 将标量分配给元组

python - 存储/检索数据结构

python - 是否可以在 python 3.2.5 中使用 PROTOCOL_TLSv1_2?

python - PyObject_GetItem 和 PyObject_SetItem 是否适用于 PyType_List 和 PyType_Dict 类型?

java - 使用 Java 8 Streams 将 List<Object> 转换为 Map<String, Integer> 使得 String 不是重复值

Python 元组列表 - 交集和并集的问题

python - 提取 numpy 数组中最小值的索引

python - 将 Thrift 客户端连接到同一主机上不同 docker 容器中的 Thrift 服务器

java - 如何在 ArrayList 中保留唯一值的原始顺序?

methods - 对可变结构参数的元组赋值