[英]How to get min key value pair in hash
我想获取哈希值中的最小值。
输入:
test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03, 'f' => 0.02, 'g'=> 0.1}
预期结果:
{'f'=> 0.02}
我怎样才能得到预期的结果?
我需要所有最小的键/值对。 如果{'a'=>1,'b'=>1,'c'=>2}
,预期结果应为{'a'=>1,'b'=>1}
。
[test.min_by{|k, v| v}].to_h
test.group_by(&:last).min_by(&:first).last.to_h # => {"f"=>0.02}
要么
test.group_by(&:last).min_by(&:first).last.to_h # => {"f"=>0.02}
test.select { |_, v| v == test.values.min }
为了提高效率:
min_val = test.values.min
test.select { |_, v| v == min_val }
根据您的数据
在Ruby控制台上运行以下命令: -
test = {'a'=> 1, 'b'=> 2, 'c' => 0.4, 'd' => 0.32, 'e' => 0.03,
'f' => 0.02, 'g'=> 0.1}
Hash[*test.sort_by(&:last)[0]]
产量将按照您的预期
=> {"f"=>0.02}
您也可以在不使用.min
方法的情况下实现此目的:
def min_key_value_pair (test)
if test == {}
return nil
else
test = test.sort_by {|k, v| v}
test[0]
end
end
我必须为我正在上课的课程做类似的事情。 我们还必须返回JUST THE KEY。 为什么你会做同样的事情只返回test[0][0]
希望这是有帮助的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.