python中保持列表顺序去重,首选dict.fromkeys()(python 3.7+),一行实现且高效;含不可哈希元素时用循环+set;兼容旧版本则用ordereddict.fromkeys()。

Python中保持列表顺序去重,核心是“不打乱原有位置的前提下剔除重复项”。直接用 set() 会丢失顺序,而用循环+判断或字典(Python 3.7+)可高效解决。
用 dict.fromkeys() 最简实现
利用字典键的唯一性和插入顺序保留特性(Python 3.7+保证有序),一行搞定:
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5] unique_lst = list(dict.fromkeys(lst)) # 结果:[3, 1, 4, 5, 9, 2, 6]
✅ 优点:简洁、高效、可读性强;❌ 注意:仅适用于元素可哈希(如 int、str、tuple),不支持 list、dict 等不可哈希类型。
用循环 + in 判断(通用兼容方案)
适合含不可哈希元素(如嵌套列表)的场景,逻辑清晰,兼容性最强:
立即学习“Python免费学习笔记(深入)”;
def ordered_unique(seq):
seen = set()
result = []
for item in seq:
if item not in seen:
seen.add(item)
result.append(item)
return result
<p>data = [[1, 2], [3, 4], [1, 2], [5, 6]]
ordered_unique(data) # [[1, 2], [3, 4], [5, 6]]- 用 set 加速查找(
in平均 O(1)) - 对不可哈希对象,需改用
not any(item == x for x in seen),但性能下降明显
用 collections.OrderedDict(兼容旧版本)
Python 3.6 及更早版本中,dict 不保证顺序,此时可用 OrderedDict 替代:
from collections import OrderedDict lst = ['a', 'b', 'a', 'c'] list(OrderedDict.fromkeys(lst)) # ['a', 'b', 'c']
⚠️ 注意:Python 3.7+ 已无需此写法,dict 更轻量、更推荐。
按需选择:性能与可读性的平衡
- 元素全为可哈希类型 → 优先用
list(dict.fromkeys(lst)) - 含不可哈希对象(如 list/dict)→ 用显式循环 +
set记录已见项 - 需兼容 Python OrderedDict.fromkeys()
- 去重同时要统计频次或做其他处理 → 直接遍历并扩展逻辑更灵活
不复杂但容易忽略:顺序去重本质是「首次出现优先」,所有方法都围绕这个原则展开。选对工具,既省代码又保效率。










