[英]How can I compare two lists in python and return matches by email
I want to compare email into both list and put into new list, 我想将电子邮件比较成两个列表,然后放入新列表,
a = [('abc@gmail.com',5),('xyz@gmail.com',6),('pqr@gmail.com',8)]
b = [('ABC','abc@gmail.com'),('XYZ','xyz@gmail.com'),('PQR','pqr@gmail.com')]
would return [('ABC',5),('XYZ',6),('PQR',8)]
, for instance. 例如,将返回[('ABC',5),('XYZ',6),('PQR',8)]
。
Lookup in a list for each item if not already ordered is O(n) complexity and is not an ideal data structure for the process 如果尚未订购,则在列表中查找每个项目的复杂度为O(n),并且不是该过程的理想数据结构
It would be beneficial if you would convert the list you would be using for lookup converted to a dictionary 如果将要用于查找的列表转换为字典,那将是有益的
d_a = dict(a)
subsequent to which the lookup is both efficient and elegant 之后的查询既高效又优雅
>>> [(key, d_a[value]) for key, value in b if value in d_a]
[('ABC', 5), ('XYZ', 6), ('PQR', 8)]
You should also take into consideration for negative case when the lookup key may not match or is present in the lookup list 当查找关键字可能不匹配或出现在查找列表中时,还应考虑否定情况
Sorting both lists and using list comprehension: 对两个列表进行排序并使用列表理解:
a = [('abc@gmail.com',5),('xyz@gmail.com',6),('pqr@gmail.com',8)]
b = [('ABC','abc@gmail.com'),('XYZ','xyz@gmail.com'),('PQR','pqr@gmail.com')]
result = [(y[0],x[1]) for x,y in zip(sorted(a,key=lambda s:s[0])), sorted(b,key=lambda s:s[1])) if x[0]==y[1]]
list a
is sorted based on first element( s[0]
) of each tuple. list a
根据每个元组的第一个元素( s[0]
)进行排序。
list b
is sorted based on second element( s[1]
) of each tuple. list b
是基于每个元组的第二个元素s[1]
排序的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.