【发布时间】:2018-02-10 23:00:22
【问题描述】:
这可能是重复的,所以如果我没有找到任何东西,请告诉我。
我的问题在标题中。
我知道下面的代码会做到这一点,但我不认为应该这样做。可以将其压缩为执行相同操作的更清洁功能吗?那么内置函数呢?
def find_sorted_avg(dict_list, key):
total = 0
for item in dict_list:
total += item[key]
return total / len(dict_list)
如果您知道更好的方法,请告诉我。
【问题讨论】:
-
您能否提供
dict_list的示例,以及您期望的输出是什么?如果此代码有效,您可能需要查看Code Review。 -
应该更好:
total = sum(item[key] for item in dict_list) / len(dict_list) -
你的意思是
total += item[key] -
@jacoblaw 可能!已编辑(否则不起作用)
-
感谢您的编辑。那是一个错字。我接受了你的回答,这似乎是完成这个的最“pythonic”的方式。
标签: python python-3.x dictionary iterator iteration