python:比较两个列表并按顺序返回匹配项

python: compare two lists and return matches in order

我有两个长度不等的列表,我想按照第一个列表中的顺序比较和提取匹配的值,所以在本例中是。

1
2
a = ['a','s','d','f']
b = ['e','d','y','a','t','v']

预期输出:

1
['a','d']

我是这样做的,但我忘了那套不能维持秩序!如何编辑下面的代码以保留订单。

1
 set(a).intersection(b)

链接到这个,我如何比较python中的两个列表并返回匹配项


b转换为集合,然后循环遍历a的项,并检查它们是否存在于该集合中:

1
2
3
>>> s = set(b)
>>> [x for x in a if x in s]
['a', 'd']

您需要使用集合:

1
2
3
4
>>> a = ['a','s','d','f']
>>> b = ['e','d','y','a','t','v']
>>> sorted(set(a) & set(b), key=a.index) # here sorting is done on the index of a
['a', 'd']


1
2
3
4
5
a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
st_b = set(b)
print([ele for ele in a if ele in st_b])
['a', 'd']

1
2
3
4
5
6
7
8
a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
matches=[]
for item_a in a:
    for item_b in b:
        if item_a == item_b:
            matches.append(item_a)
print(matches)