我有两个清单list1
和list2
。我在stackoverflow上发现了一种非常简单的方法来获取这两个列表中的公共元素,如下所示result = list(set(list1) & set(list2))
。不幸的是,这样一来,结果列表中元素的顺序就无法保留。
例如:
list1 = ['a', 'e', 't', 'b', 'c']
list2 = ['e', 'b', 'a', 'c', 'n', 's']
我希望结果(公共元素)['e', 'a', 'b', 'c']
按此顺序排列。例如,因为“ e”在列表1和列表2中,并且在列表1中的位置2和列表2中的位置1,而“ a”在列表1和列表2中,并且在列表1中的位置1和列表2中的位置3,因为2 + 1 <1 + 3,所以'e'在'a'之前。
那么,是否有任何简单的方法在两个列表之间具有公共元素并保留元素的顺序?
list1 = ['a', 'e', 't', 'b', 'c']
list2 = ['e', 'b', 'a', 'c', 'n', 's']
weights = defaultdict(int)
for i, e in enumerate(list1):
weights[e] += i
for i, e in enumerate(list2):
weights[e] += i
>>> result = sorted(set(list1) & set(list2), key=lambda i: weights[i])
>>> result
['e', 'a', 'b', 'c']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句