gpt4 book ai didi

python - python列表中的独特项目

转载 作者:太空狗 更新时间:2023-10-30 01:43:04 24 4
gpt4 key购买 nike

我正在尝试在 Python 列表中创建一个唯一的日期集合。

只有在集合中不存在日期时才将日期添加到集合中。

timestamps = []

timestamps = [
'2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13',
'2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30',
'2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']

date = "2010-11-22"
if date not in timestamps:
timestamps.append(date)

我将如何对列表进行排序?

最佳答案

您可以为此使用集合。

date = "2010-11-22"
timestamps = set(['2011-02-22', '2011-02-05', '2011-02-04', '2010-12-14', '2010-12-13', '2010-12-12', '2010-12-11', '2010-12-07', '2010-12-02', '2010-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'])
#then you can just update it like so
timestamps.update(['2010-11-16']) #if its in there it does nothing
timestamps.update(['2010-12-30']) # it does add it

关于python - python列表中的独特项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5166569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com