繁体   English   中英

从一组键创建一个散列

[英]Create a hash from an array of keys

我查看了 SO 中的其他问题,但没有找到我的具体问题的答案。

我有一个数组:

a = ["a", "b", "c", "d"]

我想将此数组转换为散列,其中数组元素成为散列中的键,并且所有相同的值都表示为 1。即散列应该是:

{"a" => 1, "b" => 1, "c" => 1, "d" => 1}

我的解决方案,其中之一:-)

a = ["a", "b", "c", "d"]
h = Hash[a.map {|x| [x, 1]}]

有几种选择:

  • to_h带块:

     a.to_h { |a_i| [a_i, 1] } #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
  • product + to_h

     a.product([1]).to_h #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
  • transpose + to_h

     [a,[1] * a.size].transpose.to_h #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}
a = ["a", "b", "c", "d"]

4 个更多选项,实现所需的输出:

h = a.map{|e|[e,1]}.to_h
h = a.zip([1]*a.size).to_h
h = a.product([1]).to_h
h = a.zip(Array.new(a.size, 1)).to_h

所有这些选项都依赖于Array#to_h ,在 Ruby v2.1 或更高版本中可用

a = %w{ a b c d e }

Hash[a.zip([1] * a.size)]   #=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1, "e"=>1}

这里:

theHash=Hash[a.map {|k| [k, theValue]}]

这假设,根据您上面的示例, a=['a', 'b', 'c', 'd']theValue=1

["a", "b", "c", "d"].inject({}) do |hash, elem|
  hash[elem] = 1
  hash
end
a = ['1','2','33','20']

Hash[a.flatten.map{|v| [v,0]}.reverse]
{}.tap{|h| %w(a b c d).each{|x| h[x] = 1}}
a = ["a", "b", "c", "d"]
h = a.inject({}){|h,k| h[k] = 1; h}
#=> {"a"=>1, "b"=>1, "c"=>1, "d"=>1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM