list_0 = [1, 2, 2, 3, 4, 4, 5]
list = []
#去除重复项
方法一:集合(set)
list_0 = [1, 2, 2, 3, 4, 4, 5]
list = list(set(list_0))
优点:
- 代码简洁
- 运行速度快
缺点:
- 顺序改变
方法二:列表推导式
list_0 = [1, 2, 2, 3, 4, 4, 5]
list = []
[answer.append(i) for i in list_0 if i not in list]
优点:
- 代码简洁
- 保持原始顺序
缺点:
- 对于大数据集,执行速度较慢,因为对于每个元素都需要检查它是否已经在结果列表中。
方法三:使用if语句和for语句
list_0 = [1, 2, 2, 3, 4, 4, 5]
list = []
for item in list_0:
if item not in list:
list.append(item)
优点:
- 保持原始顺序。
- 对于小到中等大小的数据集,执行速度尚可。
缺点:
- 对于大数据集,执行速度较慢,因为对于每个元素都需要检查它是否已经在结果列表中。
方法四:使用OrderedDict
from collections import OrderedDict
list_0 = [1, 2, 2, 3, 4, 4, 5]
list = list(OrderedDict.fromkeys(list_0))
优点:
- 保持原始顺序。
- 对于大数据集,执行速度比列表推导式和
for
循环方法快。
缺点:
- 需要导入额外的模块。
-
Python 3.1+