Python:比较两个列表并返回按顺序匹配的内容。

4

我有两个长度不相等的列表,我想比较并按照第一个列表的顺序提取匹配的值,例如在这个例子中是a。

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

期望输出:

['a','d']

我以前是这样做的,但我忘记了set不保留顺序!如何编辑下面的代码以保留顺序。
 set(a).intersection(b)

与此相关的链接:如何在Python中比较两个列表并返回匹配项


1
预期输出是什么? - Tim
2
订单是如何定义的? - _ - Oleh Prypin
在“a”中找到的顺序 - Boosted_d16
你会优先考虑哪个列表的顺序? - Hackaholic
4个回答

8

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

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

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

如果 a = ['a','s','d','a'] 呢? - Matthias
我期望得到 ['a', 'd', 'a'],但这个问题可能是学术性的。 - Matthias

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

1
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接