我想连接一个散列的键和一个列表
示例:
a={"aa"=>[1, 2], "bbb"=>[3, 4, 5], "c"=>[6, 7, 8], "hh"=>[9]}
b=["aa","c"](b列表的元素将始终以散列形式出现)
我想用散列连接一个列表,并保留散列的值。因此,我需要获取以下内容:
c={"aa"=>[1,2],"c"=>[6,7,8]}做这件事最快的方法是什么?我的a哈希可以包含多达110.000个键。
提前感谢
发布于 2013-05-24 22:31:06
a = {"aa"=>[1, 2], "bbb"=>[3, 4, 5], "c"=>[6, 7, 8], "hh"=>[9]}
b = ["aa", "c"]
a.select{|k,v| b.include? k}
#=> {"aa"=>[1, 2], "c"=>[6, 7, 8]} 你应该考虑使用集合,因为它在语义上是正确的,并且比Array#include?中的线性搜索要好得多。
require 'set'
a = {"aa"=>[1, 2], "bbb"=>[3, 4, 5], "c"=>[6, 7, 8], "hh"=>[9]}
b = Set.new ["aa", "c"]
a.select{|k,v| b.include? k}
#=> {"aa"=>[1, 2], "c"=>[6, 7, 8]} 发布于 2013-05-24 22:44:36
c = b.reduce({}) { |memo,x| memo[x]=a[x]; memo }
# => {"aa"=>[1, 2], "c"=>[6, 7, 8]} 编辑只是为了好玩,这里是几个策略的基准:"reduce","each“和"set":
require 'benchmark'
require 'set'
a = {"aa"=>[1, 2], "bbb"=>[3, 4, 5], "c"=>[6, 7, 8], "hh"=>[9]}
b = ["aa", "c"]
n = 1_000
Benchmark.bm(8) do |x|
x.report("reduce:") { n.times { b.reduce({}) { |memo,x| memo[x]=a[x]; memo } } }
x.report("each:") { n.times { c={}; b.each{|key| c[key] = a[key]} } }
x.report("set:") { n.times { bset=Set.new ['aa','c']; a.select{|k,v| bset.include? k} } }
end看起来对于这个愚蠢的基准测试,"each“是最有效的:
user system total real
reduce: 0.000000 0.000000 0.000000 ( 0.003384)
each: 0.010000 0.000000 0.010000 ( 0.002549) # <-- winner!
set: 0.010000 0.000000 0.010000 ( 0.012549)发布于 2013-05-24 22:44:49
遍历数组:
a={"aa"=>[1, 2], "bbb"=>[3, 4, 5], "c"=>[6, 7, 8], "hh"=>[9]}
b=["aa","c"]
c = {}
b.each{|key| c[key] = a[key]}
#=>{"aa"=>[1, 2], "c"=>[6, 7, 8]}https://stackoverflow.com/questions/16737356
复制相似问题