julia - 如何找到字典的最小值/最大值的键? [英] julia - How to find the key for the min/max value of a Dict?

查看:18
本文介绍了julia - 如何找到字典的最小值/最大值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 julia 中找到与字典的最小值或最大值对应的键.在 Python 中,我会执行以下操作:

I want to find the key corresponding to the min or max value of a dictionary in julia. In Python I would to the following:

my_dict = {1:20, 2:10}
min(my_dict, my_dict.get)

这将返回密钥 2.

我怎样才能在 julia 中做同样的事情?

How can I do the same in julia ?

my_dict = Dict(1=>20, 2=>10)
minimum(my_dict)

后者返回 1=>20 而不是 2=>10 或 2.

The latter returns 1=>20 instead of 2=>10 or 2.

推荐答案

另一种选择是:

collect(keys(d))[indmin(collect(values(d)))]

它取决于键和值迭代器的属性,这些属性不能保证,但实际上适用于 Dicts(并且 保证了 OrderedDicts).像 reduce 答案一样,d 必须是非空的.

it depends on properties of keys and values iterators which are not guaranteed, but in fact work for Dicts (and are guaranteed for OrderedDicts). like the reduce answer, d must be non-empty.

为什么要提到这个,当 reduce 非常准确?它快 3 到 4 倍(至少在我的电脑上)!

why mention this, when the reduce, pretty much nails it? it is 3 to 4 times faster (at least on my computer) !

这篇关于julia - 如何找到字典的最小值/最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆