我有一本订好的字典:
{'20140106': '82.1000000',
'20140217': '77.0300000',
'20140224': '69.6200000',
'20140310': '46.3300000',
'20140414': '49.3800000',
键是日期:yyyy-mm-dd,我想在一个键中存储一个月的所有值:
^{pr2}$我意识到这个不太好的解决方案:
val = [] #list, where i put all values for an exact month
previus_key = list(collection.keys())[0]
val.append(collection.get(previus_key))
for key in list(collection.keys())[1:]:
if (key[4:6]==previus_key[4:6]): #if it's the same month
val.append(list(collection.pop(key))) #remember the value and delete an item
else:
collection.update({previus_key:val}) #that means, we jumped to another month, so lets update the values for previus month
previus_key = key #now, start the same algorihtm for a new month.
val = collection.get(previus_key)
但是,我得到一个错误:'str' object has no attribute 'append'
的行
val.append(list(collection.pop(key)))
。我研究了一下,得出结论,它一定不在这里!因为,我把一个列表附加到一个列表中!
所以,请指出我的错误并给出建议,我怎样才能使代码更漂亮。谢谢!在
我不认为在这里使用字符串作为键来表示日期有任何好处。这是我的解决方案,但我希望它不会破坏您当前的代码。在
好吧,你的代码显示你在那里做了很多嵌套:
以及:
以下是一种方法: 为此使用元组:
^{pr2}$你不仅简化了代码,还简化了代码:
虽然键只能是不可变的对象,但是元组是不可变的对象。在
为什么不使用}函数。
reduce
和{reduce
将对迭代对象中的每个项应用一个函数,您还可以指定reduce
的初始值我认为问题出在你代码的最后一行。您确实在那里为变量
var
分配了一个字符串。在编辑:这里有一个建议,它与您的原始代码很接近。
三件事: 1) 这里的结果是一个新的字典,而不是相同的实例,因为我发现它通常更可取。 2) 钥匙只有年份和月份,因为日期无关紧要。 3) 所有的值都是列表,而不是字符串和列表的混合。在
相关问题 更多 >
编程相关推荐