从 Perl 中的哈希中获取具有最高值的键的最简单方法是什么?
从 Perl 中的哈希中获取具有最高值的键的最简单方法是什么?
What is the easiest way to get a key with the highest value from a hash in Perl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
虽然在其他一些答案中找到的 sort: 解决方案
非常优雅,但它的性能并不像看起来那么好。首先,排序将
O(n)
搜索操作转换为O(n log n)
操作。其次,排序解决方案具有n log n
哈希查找。哈希查找对于某些操作非常有用,但是在处理整个哈希时,查找将比使用each
、keys
或value 慢
迭代数据结构。这是因为迭代器不需要计算键的哈希值,也不需要重复遍历 bin 来查找值。而且开销不是恒定的,而是随着哈希值变大而增加。这里有一些更快的解决方案:
这是一个使用
each
迭代器的解决方案(O(1)
操作完成n
次):或者以内存换取速度的更快版本(它会复制哈希值):
这是不同哈希大小的性能:
如您所见,如果内存不是太大问题,则具有内部数组的版本是最快的,接近的接下来是
each
迭代器,在遥远的第三个......sort
While the solution with sort:
found in some of the other answers is quite elegant, it doesn't perform as nicely as it looks. First off, the sort transforms an
O(n)
search search operation into anO(n log n)
one. Secondly, the sort solution hasn log n
hash look-ups. Hash look-ups are very good for certain operations, but when working with the entire hash, look-ups will be slower than usingeach
,keys
, orvalues
to iterate through the data structure. This is because the iterators do not need to calculate the hashes of keys, nor do they need to repeatedly walk through bins to find the values. And the overhead is not constant, but increasing as the hashes get larger.Here are a few faster solutions:
Here is a solution using the
each
iterator (anO(1)
operation donen
times):Or a faster version that trades memory for speed (it makes a copy of the hash):
Here is the performance with various hash sizes:
As you can see, if memory isn't much of an issue, the version with internal arrays is fastest, closely followed by the
each
iterator, and in a distant third...sort
不知道为什么每个人都用手做这个......
Not sure why everyone is doing this by hand...
与对哈希进行排序的其他答案相比,以下内容更节省空间,并且将以 O(n) 而不是 O(n log n) 的速度运行。它假设值是大于 0 的整数,并且哈希值不为空,但应该可以轻松地根据您的情况进行扩展。
$key_for_max_value 现在将是对应于最高值的键。
The following is more space-efficient and will run in O(n) instead of O(n log n) as compared to the other answers which sort the hash. It assumes values are integers greater than 0 and the hash is not empty, but should be easily extended for your case.
$key_for_max_value will now be the key corresponding to the highest value.
按值排序的键,从最低到最高:
按值排序的键,从最高到最低:
第一个元素
将太空飞船替换为
cmp
。The keys sorted by value, from lowest to highest:
The keys sorted by value, from highest to lowest:
And the first element
Replace the spaceship with
cmp
to taste.很可能就是你想要的。
如果你有一个非常大的哈希值,你可能需要使用类似 Schwartzian 变换的东西:
is likely to be what you want.
If you have a very large hash, you might want to use something like a Schwartzian transform:
如果性能不是问题,我建议采用更文学编程< /a> 解决方案。
If performance isn't an issue, I'd suggest a more literate programming solution.