查找字典数组中的最小值
我有一个如下所示的数组:
people = [{'node': 'john', 'dist': 3},
{'node': 'mary', 'dist': 5},
{'node': 'alex', 'dist': 4}]
我想计算所有“dist”键的最小值。例如,在上面的例子中,答案是3。
我写了下面的代码:
min = 99999
for e in people:
if e[dist] < min:
min = e[dist]
print "minimum is " + str(min)
我想知道是否有更好的方法来完成这个任务。
I have an array like the following:
people = [{'node': 'john', 'dist': 3},
{'node': 'mary', 'dist': 5},
{'node': 'alex', 'dist': 4}]
I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3.
I wrote the following code:
min = 99999
for e in people:
if e[dist] < min:
min = e[dist]
print "minimum is " + str(min)
I am wondering if there is a better way to accomplish this task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
min
函数:Use the
min
function:您可以使用生成器表达式创建包含所有键的列表,然后使用内置的 min 函数:
You could use a generator expression to create a list with all keys and then use the built-in min function: