降低哈希值 [英] Reduce Hash Values

查看:120
本文介绍了降低哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用reduce的语法时遇到麻烦.我有以下格式的哈希:

I am having trouble with the syntax for reduce. I have a hash of the following format:

H = {"Key1" => 1, "Key2" => 2}

我想使用reduce来查找此函数中值的总和.

I would like to use reduce to find the sum of the values in this function.

类似

H.reduce(0) {|memo, elem| memo+=elem}

我知道这是错误的.我不明白如何使elem成为哈希值.

I know this is wrong. I dont understand how I can make elem the value of the hash.

推荐答案

使用 Enumerable#reduce ,如果您可以在散列碰巧为空的情况下获取nil,则可以:

H.values.reduce(:+) # => 3
Hash.new.values.reduce(:+) # => nil

要在散列为空时安全地获取0,请使用:

To safely get 0 when the hash is empty, use:

H.values.reduce(0) { |sum,x| sum + x } # or...
H.reduce(0) { |sum,(key,val)| sum + val } # ...if you need to inspect the key

这是踢脚的快速基准.请注意,似乎只减少值而不是键/值对中的值会更快:

Here's a quick benchmark, for kicks. Note that it appears to be slightly faster to reduce just the values rather than values from the key/value pairs:

                               user     system      total        real
H.values.reduce(:+)        4.510000   0.080000   4.590000 (  4.595229)
H.values.reduce(0) {...}   4.660000   0.080000   4.740000 (  4.739708)
H.reduce(0) {...}          5.160000   0.070000   5.230000 (  5.241916)

require 'benchmark'

size = 1_000
hash = Hash[* Array.new(size*2) { rand } ]

N=10_000
Benchmark.bm(24) do |x|
  x.report('H.values.reduce(:+)')      { N.times { hash.dup.values.reduce(:+) } }
  x.report('H.values.reduce(0) {...}') { N.times { hash.dup.values.reduce(0) { |sum,x| sum + x } } }
  x.report('H.reduce(0) {...}')        { N.times { hash.dup.reduce(0) { |sum,(_,v)| sum + v } } }
end

这篇关于降低哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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