[英]Unique items in python list
我試圖在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)
我該如何排序?
你可以使用套裝。
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
這段代碼實際上什么都不做。 您正在引用相同的變量兩次( 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)
你的病情似乎是正確的。 如果您不關心日期的順序,則使用集合而不是列表可能更容易。 你不需要任何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.