在 Perl 中,如何打印哈希中最大值对应的键?
如何仅打印哈希的第一个键和元素?
我已经有一个排序的哈希,但我只想打印第一个键和相应的值 谢谢,
感谢大家,最后我将键和值推送到两个不同的 @array 并打印每个数组的元素 0 并且它有效:)
How can I print only the first key and element of my hash?
I have already a sorted hash, but I want to print only the first key and respective value
thanks,
Thanks to all of you at the end I push the keys and the values to two different @array and print element 0 of each array and it works :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
哈希值具有无序的键。因此,哈希中不存在第一个键这样的键。
但是,如果您需要首先排序的键(以获得最大键值):
请记住使用
<=>
而不是cmp
进行数字排序。Hashes have unordered keys. So, there is no such key as a first key in a hash.
However, if you need the key that sorts first (for maximum key value):
Remember to use
<=>
instead ofcmp
for numerical sorting.在 Perl 哈希中,键没有排序。使用 sort 函数按您想要的顺序获取键,或者您可以按键创建哈希时将其放入数组中,并且您的第一个键将位于数组中的第零个索引中
您可以使用下面的代码,我假设哈希名称是 my_hash,键和值是数字。如果您有字符串,则可以使用
cmp
而不是<=>
。更多详情请参阅排序文档获取最大值键
获取最大值对应的键
In perl hashes there is no ordering for keys. Use sort function to get the keys in the order that you want or you can push the keys into an array as you create the hash and your first key will be in zero th index in the array
You can use the below code, i am assuming hash name is my_hash and keys and values are numbers. If you have strings, you can use
cmp
instead of<=>
. Refer to the sort documentation for more detailsGet the max key
Get the key corresponding to the max value
对于大型哈希,如果您出于任何其他原因不需要排序的键,那么最好避免排序。
如果您打算排序,则只需要具有最大值的键,而不是
keys
和values
的整个数组:For large hashes, if you do not need the sorted keys for any other reason, it might be better to avoid sorting.
If you are intent on sorting, you only need the key with the maximum value, not the entire arrays of
keys
andvalues
:正如艾伦所写 - 散列没有特定的顺序,但您可以对散列键进行排序:
或者,如您所愿,从键数组中获取第一个元素:
Just as Alan wrote - hashes don't have specific order, but you can sort hash keys:
or, as you wish, get first element from keys array: