简体   繁体   English

如何比较python中的两个列表并通过电子邮件返回匹配项

[英]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.

相关问题 如何比较python中的两个列表并返回不匹配 - How can I compare two lists in python and return not matches 如何比较python中的两个列表并返回匹配项 - How can I compare two lists in python and return matches 如果每个字符串中的索引匹配,如何按索引比较两个 python 列表返回 Boolean? - How can I compare two python lists by index return a Boolean if the index in each string matches? python:比较两个列表并按顺序返回匹配项 - python: compare two lists and return matches in order 如何比较两个字符串列表并返回匹配项 - How to compare two lists of strings and return the matches 如何比较两个不同大小的列表,找到匹配项并在两个列表中返回这些匹配项的索引 - How do I compare two lists of diffrent sizes, find matches and return the indices of those matches in both lists 我如何比较 python 中的两个列表,如果我有匹配项 ~> 我想要另一个列表中的匹配项和下一个值 - how can I compare two lists in python and if I have matches ~> I want matches and next value from another list 我如何比较python中的两个列表,并返回第二个需要具有相同值而不管顺序? - How can I compare two lists in python, and return that the second need to have the same values regardless of order? 如何比较两个不同对象的列表并返回匹配项? - How Can i compare two lists of different objects and return match? 在Python中,如何比较两个列表并获取匹配的所有索引? - In Python, how to compare two lists and get all indices of matches?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM