如何找到在哈希阵列多键组合最大值? [英] How to find max value grouped by multiple keys in array of hashes?

查看:117
本文介绍了如何找到在哈希阵列多键组合最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个具有这种结构的数据。将在由C升序排列。

Have data that has this kind of structure. Will be in ascending order by 'c'.

[ { 'a' => 1, 'b' => 1, 'c' =>  1, 'd' => '?' },
  { 'a' => 1, 'b' => 1, 'c' =>  2, 'd' => '?' },
  { 'a' => 1, 'b' => 1, 'c' =>  3, 'd' => '?' },
  { 'a' => 1, 'b' => 2, 'c' =>  4, 'd' => '?' },
  { 'a' => 1, 'b' => 2, 'c' =>  5, 'd' => '?' },
  { 'a' => 2, 'b' => 1, 'c' =>  6, 'd' => '?' },
  { 'a' => 2, 'b' => 1, 'c' =>  7, 'd' => '?' },
  { 'a' => 2, 'b' => 1, 'c' =>  8, 'd' => '?' },
  { 'a' => 2, 'b' => 2, 'c' =>  9, 'd' => '?' },
  { 'a' => 2, 'b' => 2, 'c' => 10, 'd' => '?' } ]

希望通过'a'和'B'的每一个独特的组合,组合的'C'的最大值的数组。

Want array of the max value of 'c' grouped by each unique combination of 'a' and 'b'.

[ { 'a' => 1, 'b' => 1, 'c' =>  3, 'd' => '?' },
  { 'a' => 1, 'b' => 2, 'c' =>  5, 'd' => '?' },
  { 'a' => 2, 'b' => 1, 'c' =>  8, 'd' => '?' },
  { 'a' => 2, 'b' => 2, 'c' => 10, 'd' => '?' } ]

其他键需要保留,但不另外涉及到的转变。我能想出迄今最好的是扭转阵列(从而降序按C订购),由'A'的'B'uniq的,然后再反向数组。但我根据uniq_by的实现总是返回找到的第一个独特的项目。该规范并没有说,所以我很担心依靠这种行为,因为它可能在未来的版本中改变。也想知道这可能是一个非常低效的方法。

The other keys need to be retained but are not otherwise related to the transformation. The best I could figure out so far is to reverse the array (thus descending ordered by 'c'), uniq by 'a' an 'b', and reverse array again. But I am depending on the implementation of uniq_by always returning the first unique item found. The specification doesn't say that, so I am worried about relying on that behavior since it could change in future versions. Also wondering if this may be a really inefficient method.

@data.reverse!.uniq!{|record| [record['a'],record['b']]}.reverse!

有没有更好的,更有效的方式来做到这一点?如果你有更好的方法,你能不能也请解释它,而不是只给我一个超级讨厌的单行,我可能无法破译。

Is there a better and more efficient way to do this? If you do have a better way, can you also please explain it instead of just giving me a super nasty one-liner that I may not be able to decipher.

推荐答案

这实际上相当简单:

a.group_by { |h| h.values_at("a", "b") }.map { |_, v| v.max_by { |h| h["c"] } } 

或用更好的格式:

a.group_by do |h|
  h.values_at("a", "b") 
end.map do |_, v| 
  v.max_by { |h| h["c"] }
end

解释:首先我们使用可枚举#GROUP_BY 创建哈希与组合b(与哈希#提取values​​_at )作为键和所有哈希与该组合的价值。然后,我们映射在这个哈希,忽略键和选择具有最大值的元素为C从的Enumerable#max_by

Explanation: first we use Enumerable#group_by to create a Hash with the combinations of "a" and "b" (extracted with Hash#values_at) as the keys and all hashes with that combination as the values. We then map over this hash, ignore the keys and select the element with the maximum value for "c" from the array with Enumerable#max_by.

这篇关于如何找到在哈希阵列多键组合最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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