python - 从两个列表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方法返回有序集合,但我需要保持元素的顺序。
有更好的方法吗?
解决方案
在迭代列表时编辑列表是不好的做法,但这里有一个列表理解来做你想做的事。这也将保持订单。
>>> 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]
推荐阅读
- python - Python - 从没有熊猫的 excel 中读取并插入 Postgre
- swift - 将 Optional(Set(["6", "14"])) 转换为 [String]
- python - 如何从 matplotlib.figure.Figure 的列表中保存 matplotlib 图?
- sql - Sybase Iq 数据库中的空值大小
- coq - 文章同伦类型理论和 Voevodsky 的单价基础的 coq 代码
- r - 使用 dplyr 的 transmute_all 将列值替换为列名
- javascript - 从图像中获取日期
- java - 如何向 Eclipse e4 RCP 应用程序添加依赖项?
- javascript - Reatcjs 访问数组和嵌套对象中的对象属性
- node.js - MongoDb : Mongoose 将不同集合中的元素添加到另一个集合