python列表中的唯一项目

时间:2011-03-02 11:04:32

标签: 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)

我如何对列表进行排序?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分: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")