繁体   English   中英

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

[英]python: compare two lists and return matches in order

我有两个不等长的列表,我想按照第一个列表的顺序比较和拉出匹配的值,所以在这个例子中。

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

预期产量:

['a','d']

我是这样做的,但我忘记了套装不保留订单! 如何编辑下面的代码以保留订单。

 set(a).intersection(b)

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

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

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

你需要使用set:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM