[英]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)
将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.