有没有办法在Python中比较列表,类似于excel中的vlookup。

问题描述 投票:0回答:1

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
1个回答
1
投票

下面是一个简单的使用list-comprehension的单行本。

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']

0
投票

你可以使用pandas库很容易地实现这一点。

import pandas as pd

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

s1 = pd.Series(list1)
print(s1.isin(list2))

输出。

0    False
1     True
2     True
3     True
4    False
5    False
6    False
dtype: bool

这里pandas返回通用的 True/False 而不是您建议的foundnot-found。

: 尽量使用矢量化的实现,和库的实现,而不是自己写代码,因为这些代码一般都是相当快和准确的实现。

© www.soinside.com 2019 - 2024. All rights reserved.