0
的理解行爲我有星期幾的有序詞典:需要幫助Ordereddict
weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])
我想第n個鍵的值更改爲1,所以如果我n設置爲4,第4個鍵是'星期四',所以平日裏就變成了:
OrderedDict([('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 1), ('Fri', 0), ('Sat', 0), ('Sun', 0)])
我可以做到這一點下面的代碼:
startday_2017 = 4
weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])
date = list(weekdays.keys())[(startday_2017-1)]
for key in weekdays.keys():
if key == date:
weekdays[key] = 1
,似乎工作,但如果I W螞蟻在第n個鍵之前或之後更改與鍵對應的值時,ordereddict開始變得有趣。有了這個代碼:
startday_2017 = 4
weekdays = collections.OrderedDict([ ('Mon', 0), ('Tue', 0), ('Wed', 0), ('Thu', 0), ('Fri', 0), ('Sat', 0), ('Sun', 0) ])
date = list(weekdays.keys())[(startday_2017-1)]
for key in weekdays.keys():
if key < date:
weekdays[key] = "applesauce"
elif key == date:
weekdays[key] = 1
else:
weekdays[key] = 2
print(weekdays)
我得到這樣的輸出:
OrderedDict([('Mon', 'applesauce'), ('Tue', 2), ('Wed', 2), ('Thu', 1), ('Fri', 'applesauce'), ('Sat', 'applesauce'), ('Sun', 'applesauce')])
如何實現結果我之後?