在2个不同长度的列表中查找匹配项

时间:2014-08-04 00:59:29

标签: python list compare

我有2个列表列表,第一个名为'BIG_LIST'的列表如下:

['324','1','Bob Smith','Manager','320','T5'],['323','1','Jim Crabtree','Manager','320','T4'],['322','2','Jane Copeland','Student','120','F5'],['314','1','Harry Rice','Manager','300','T1'],... and so on

第二个名为'CHECK_EXIST'的列表如下所示:

['Jane Doe','AYT34','Y'],['John Doe','HF234','Y'],['Bob Smith','YGS4','Y'],['Harry Rice','HHS334','Y']

如果他们的名字存在于'CHECK_EXIST'中,我想将整行保留在'BIG_LIST'中。名称是'BIG_LIST'中的第3个元素,'CHECK_EXIST'中是第1个元素。我一直在尝试列表推导,但没有得到数据。

matches = []
matches = [i for i in BIG_LIST if BIG_LIST[2] in CHECK_EXIST]
print matches

输出为空白

$ python find_matches.py 
[]

1 个答案:

答案 0 :(得分:2)

big_list = [['324','1','Bob Smith','Manager','320','T5'],['323','1','Jim Crabtree','Manager','320','T4'],['322','2','Jane Copeland','Student','120','F5'],['314','1','Harry Rice','Manager','300','T1']]

check_exist = [['Jane Doe','AYT34','Y'],['John Doe','HF234','Y'],['Bob Smith','YGS4','Y'],['Harry Rice','HHS334','Y']]

find_matches = [row for row in big_list if any(row[2] == ele[0] for ele in check_exist) ]

print (find_matches)

[['324', '1', 'Bob Smith', 'Manager', '320', 'T5'], ['314', '1', 'Harry Rice', 'Manager', '300', 'T1']]

if any(row[2] == ele[0] for ele in check_exist)检查big_list中每个子列表的第三个元素是否等于check_exist

中每个子列表中的任何第一个元素

根据您的评论,您似乎在check_exist中有空的子列表,如果是,请更改为in ele

find_matches = [row for row in big_list if any(row[2] in ele for ele in check_exist)