如何比较Python中两个列表中的两个值

时间:2016-01-12 15:14:00

标签: python csv dictionary list-comprehension dictionary-comprehension

我尝试比较两个值,一个来自list1,另一个来自list2。每个值都存储在这些列表中的字典中。

正在从csv文件中读取数据。

目前我的代码只是比较第一个值而不是迭代:

import csv    

list1 = []
list2 = []

reader1 = csv.DictReader(open('file1.csv'))
reader2 = csv.DictReader(open('file2.csv'))

list1 = [x for x in reader1]
list2 = [x for x in reader2]

print [x['MyMail'] for x in list1 for y in list2 if x['MyMail']==y['Email']]

1 个答案:

答案 0 :(得分:0)

您想为此使用set

s1 = set([i['MyMail'].lower() for i in reader1 if i['MyMail']])
s2 = set([i['Email'].lower() for i in reader2 if i['Email']])

common_emails = s1 & s2