如何在Ruby中的哈希列表中为每个键提取更大的值 [英] How can I extract the bigger value for each key in a list of hashes in Ruby

查看:224
本文介绍了如何在Ruby中的哈希列表中为每个键提取更大的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想象有一个简单的方法来做,而不是使用许多变量和状态。



我只想得到为每个键给出的最高值散列列表



例如:

  > 19.4},{1 => 12.4},{2 => 29.4},{3 => 12.4},{2 => 39.4},{2 => 59.4}] 



结果

  {1 => 19.4},{3 => 12.4},{2 => 59.4}] 




  a = [{1 = > 19.4},{1 => 12.4},{2 => 29.4},{3 => 12.4},{2 => 39.4},{2 => 59.4}] 

#下面是主要技巧,分组散列和排序键/值对
#以**升序**。
a.sort_by(&:to_a)
#=> [{1 => 12.4},{1 => 19.4},{2 => 29.4},{2 => 39.4},{2 => 59.4},{3 => 12.4}]

#然后使用技巧,我们知道hash不能有重复的键,所以
#盲目的我可以依靠`Enumerable#inject`与`Hash#merge`方法。
a.sort_by(&:to_a).inject(:merge)
#=> {1 => 19.4,2 => 59.4,3 => 12.4}

#final one
a.sort_by(&:to_a).inject(:merge)。 map {| k,v | {k => v}}
#=> [{1 => 19.4},{2 => 59.4},{3 => 12.4}]


I can imagine there is a simple way to do that instead of use many variables and state.

I just want to get the highest value given for each key in a list of hashes

For example:

[{1=>19.4}, {1=>12.4}, {2=>29.4}, {3=>12.4}, {2=>39.4}, {2=>59.4}]

Result

[{1=>19.4}, {3=>12.4}, {2=>59.4}]

解决方案

I'd do as below :

a = [{1=>19.4}, {1=>12.4}, {2=>29.4}, {3=>12.4}, {2=>39.4}, {2=>59.4}]

# the below is the main trick, to group the hashes and sorted the key/value pair
# in **ascending order**.
a.sort_by(&:to_a)
# => [{1=>12.4}, {1=>19.4}, {2=>29.4}, {2=>39.4}, {2=>59.4}, {3=>12.4}]

# then using the trick in mind, we know hash can't have duplicate keys, so
# blindly I can rely on `Enumerable#inject` with the `Hash#merge` method.
a.sort_by(&:to_a).inject(:merge)
# => {1=>19.4, 2=>59.4, 3=>12.4}

# final one
a.sort_by(&:to_a).inject(:merge).map { |k,v| {k => v} }
# => [{1=>19.4}, {2=>59.4}, {3=>12.4}]

这篇关于如何在Ruby中的哈希列表中为每个键提取更大的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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