查找字典数组中的最小值

发布于 2024-11-15 19:49:41 字数 387 浏览 3 评论 0原文

我有一个如下所示的数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

猫腻 2024-11-22 19:49:41

使用 min 函数:

minimum = min(e['dist'] for e in people)
# Don't call the variable min, that would overshadow the built-in min function
print ('minimum is ' + str(minimum))

Use the min function:

minimum = min(e['dist'] for e in people)
# Don't call the variable min, that would overshadow the built-in min function
print ('minimum is ' + str(minimum))
客…行舟 2024-11-22 19:49:41
min(x['dist'] for x in people)
min(x['dist'] for x in people)
拧巴小姐 2024-11-22 19:49:41

您可以使用生成器表达式创建包含所有键的列表,然后使用内置的 min 函数:

min(x['dist'] for x in people)

You could use a generator expression to create a list with all keys and then use the built-in min function:

min(x['dist'] for x in people)
谈场末日恋爱 2024-11-22 19:49:41
min(people, key=lambda x:x['dist'])['dist']
min(people, key=lambda x:x['dist'])['dist']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文