Unique items in a python list.

I am trying to create a unique set of dates in a Python list.

Add a date to the collection if it is not already 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 do I sort the list?

+4
source share
3 answers

You can use a kit 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 
+14
source

This code will effectively do nothing. You are referring to the same variable twice ( timestamps ).

So, you will need to make two separate 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) 
+2
source

Your condition seems correct. If you don't need a date order, it might be easier to use a set instead of a list. In this case, you will not need 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") 
+1
source

Source: https://habr.com/ru/post/1341960/


All Articles