2011-03-02 91 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") 
相關問題