我有两个长度不相等的列表,我想比较并按照第一个列表的顺序提取匹配的值,例如在这个例子中是a。
a = ['a','s','d','f']
b = ['e','d','y','a','t','v']
期望输出:
['a','d']
我以前是这样做的,但我忘记了set不保留顺序!如何编辑下面的代码以保留顺序。
set(a).intersection(b)
与此相关的链接:如何在Python中比较两个列表并返回匹配项
我有两个长度不相等的列表,我想比较并按照第一个列表的顺序提取匹配的值,例如在这个例子中是a。
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','a']
呢? - Matthias['a', 'd', 'a']
,但这个问题可能是学术性的。 - Matthiasa = ['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)