首页 > 解决方案 > 有没有办法比较 Python 中的列表,类似于 excel 中的 vlookup

问题描述

Python 比较 list1 和 list2

list1 = [1,2,3,4,5,6,7]
list2 = [2,3,4]
list_compare = ['not-found','found','found','found','not-found','not-found','not-found']

“list1”和“list_compare”的长度应该相同,以便将其写入 csv。

标签: python

解决方案


这是一个使用列表理解的简单单行

list1= [1,2,3,4,5,6,7]
list2= [2,3,4]

compared = ['found' if x in list2 else 'not-found' for x in list1]
print(compared) #['not-found', 'found', 'found', 'found', 'not-found', 'not-found', 'not-found']

推荐阅读