Python列表中的唯一项

4
我正在尝试在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个回答

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

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)

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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接