简体   繁体   English

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

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

I have two lists of unequal length and I would like to compare and pull matched values in the order from the first list, so a in this example. 我有两个不等长的列表,我想按照第一个列表的顺序比较和拉出匹配的值,所以在这个例子中。

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

expected output: 预期产量:

['a','d']

I was doing it like this but I forgot that set doesnt retain the order! 我是这样做的,但我忘记了套装不保留订单! how can I edit my code below to retain the order. 如何编辑下面的代码以保留订单。

 set(a).intersection(b)

Linked to this How can I compare two lists in python and return matches 链接到此如何比较python中的两个列表并返回匹配项

Convert b to a set and then loop over a 's items and check if they exist in that set: b转换为一个集合,然后遍历a项目并检查它们是否存在于该集合中:

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

you need to use set: 你需要使用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.

相关问题 如何比较python中的两个列表并返回匹配项 - How can I compare two lists in python and return matches 如何比较python中的两个列表并返回不匹配 - How can I compare two lists in python and return not matches 如何比较python中的两个列表并通过电子邮件返回匹配项 - How can I compare two lists in python and return matches by email 如何比较两个字符串列表并返回匹配项 - How to compare two lists of strings and return the matches 如果每个字符串中的索引匹配,如何按索引比较两个 python 列表返回 Boolean? - How can I compare two python lists by index return a Boolean if the index in each string matches? 比较两个列表python3的元素和顺序 - Compare elements AND order of two lists python3 如何比较两个不同大小的列表,找到匹配项并在两个列表中返回这些匹配项的索引 - How do I compare two lists of diffrent sizes, find matches and return the indices of those matches in both lists Python - 比较字典列表并返回不匹配的键之一 - Python - Compare lists of dictionaries and return not matches of one of the keys 在Python中,如何比较两个列表并获取匹配的所有索引? - In Python, how to compare two lists and get all indices of matches? 我如何比较python中的两个列表,并返回第二个需要具有相同值而不管顺序? - How can I compare two lists in python, and return that the second need to have the same values regardless of order?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM