首页 > 解决方案 > 从两个列表python中获取无序的唯一元素

问题描述

如果我有两个列表(可能有不同的 len):

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = > [11, 22, 33, 44]

正在做:

for element in x:
    if element in f:
        f.remove(element)

得到

result = [11,22,33,44,4]

set方法返回有序集合,但我需要保持元素的顺序。

有更好的方法吗?

标签: pythonpython-3.xlistset

解决方案


在迭代列表时编辑列表是不好的做法,但这里有一个列表理解来做你想做的事。这也将保持订单。

>>> x = [1,2,3,4]
>>> f = [1,11,22,33,44,3,4]
>>> [a for a in f if a not in x]
[11, 22, 33, 44]

推荐阅读