Python列表中的唯一项

4 投票
3 回答
7074 浏览
提问于 2025-04-16 12:49

我想在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)

那我该怎么对这个列表进行排序呢?

3 个回答

1

你的条件看起来是对的。不过,如果你不在乎日期的顺序,使用集合(set)可能会更简单,而不是用列表(list)。在这种情况下,你就不需要任何if语句了:

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'])
timesteps.add("2010-11-22")
2

这段代码实际上不会起任何作用。你在两次引用了同一个变量(timestamps)。

所以你需要创建两个不同的列表:

unique_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):
   unique_timestamps.append(date)
14

你可以用集合来解决这个问题。

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

撰写回答