加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Ruby中的哈希列表中为每个键提取更大的值

发布时间:2020-12-17 01:50:35 所属栏目:百科 来源:网络整理
导读:我可以想象有一种简单的方法可以做到这一点,而不是使用许多变量和状态. 我只想获得散列列表中每个键的最高值 例如: [{1=19.4},{1=12.4},{2=29.4},{3=12.4},{2=39.4},{2=59.4}] 结果 [{1=19.4},{2=59.4}] 解决方法 我会这样做: a = [{1=19.4},{2=59.4}]# th
我可以想象有一种简单的方法可以做到这一点,而不是使用许多变量和状态.

我只想获得散列列表中每个键的最高值

例如:

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

结果

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

解决方法

我会这样做:

a = [{1=>19.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=>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},{3=>12.4}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读