2011-03-02 88 views
4

我想在Python列表中创建一个唯一的日期集合。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) 

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

回答

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

你的条件似乎是正确的。如果你不关心日期的顺序,可能会更容易使用一个集合而不是一个列表。在这种情况下,您不需要任何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") 
相关问题