You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何删除列表中的重复字符串 以日期列表去重为例

Python 列表重复字符串去重方案

需求说明

对存储时间字符串的列表dates进行去重处理,要求去重后每个时间字符串仅保留一个,且保留原列表的元素先后顺序。

示例输入

dates = ['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00', '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00', '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00', '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00', '2018-12-01 00:00:00', '2018-12-01 00:00:00', '2019-01-01 00:00:00']

预期输出

['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00', '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00', '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00', '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00', '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00', '2018-12-01 00:00:00', '2019-01-01 00:00:00']

实现方法

方法1:无需保留原顺序(不匹配当前需求)

直接通过集合去重,执行速度快,但会打乱原列表的元素顺序:

unique_dates = list(set(dates))

方法2:保留原顺序(适配当前需求,Python 3.7+ 版本可用)

利用Python 3.7+版本字典默认保留插入顺序的特性,一行代码完成去重,性能优秀:

unique_dates = list(dict.fromkeys(dates))

方法3:保留原顺序(全Python版本兼容)

编写通用去重函数,兼容所有Python版本,逻辑清晰易读:

def deduplicate_list(input_list):
    seen = set()
    result = []
    for item in input_list:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

# 调用方法
unique_dates = deduplicate_list(dates)

以上方法2和方法3的输出结果和预期输出完全一致。

内容的提问来源于stack exchange,提问作者georgehere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:06:02