简体   繁体   English

python列表中的唯一项目

[英]Unique items in python list

I am trying to make a unique collection of dates in a Python list. 我试图在Python列表中创建一个独特的日期集合。

Only add a date to the collection if it not already present in the collection. 仅在集合中尚未存在日期时才添加日期。

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)

How would I sort the list? 我该如何排序?

You can use sets for this. 你可以使用套装。

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

This code will effectively do nothing. 这段代码实际上什么都不做。 You are referencing the same variable twice ( timestamps ). 您正在引用相同的变量两次( timestamps )。

So you would have to make two seperate lists: 所以你必须制作两个单独的列表:

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)

Your condition seems to be correct. 你的病情似乎是正确的。 If you do not care about the order of the dates though, it might be easier to use a set instead of a list. 如果您不关心日期的顺序,则使用集合而不是列表可能更容易。 You would not need any if in this case: 你不需要任何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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM