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

时间:2014-11-28 14:21:31

标签: python list set

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

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

预期产出:

['a','d']

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

 set(a).intersection(b)

与此How can I compare two lists in python and return matches

相关联

4 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

你需要使用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']

答案 2 :(得分:2)

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

答案 3 :(得分:0)

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)