繁体   English   中英

使用数组中的键和标准值创建哈希

[英]Create hash with keys from array and a standard value

我有这样一个数组:

['a', 'b', 'c']

什么是最简单的方法:

{'a' => true, 'b' => true, 'c' => true}

true只是值应该保持的标准值。

下面怎么样?

2.1.0 :001 > ['a', 'b', 'c'].each_with_object(true).to_h
 => {"a"=>true, "b"=>true, "c"=>true} 

尝试:

Hash[ary.map {|k| [k, true]}]

从Ruby 2.0开始,您可以使用to_h方法:

ary.map {|k| [k, true]}.to_h

根据您的具体需求,您可能实际上并不需要初始化值。 你可以这样简单地创建一个默认值为true的Hash:

h = Hash.new(true)
#=> {}

然后,当您尝试访问之前不存在的密钥时:

h['a']
#=> true

h['b']
#=> true

优点:使用的内存更少,初始化速度更快。

缺点:实际上并不存储密钥,因此散列将为空,直到其他代码存储其中的值。 如果您的程序依赖于从散列中读取键或想要遍历散列,那么这只会是一个问题。

['a', 'b', 'c'].each_with_object({}) { |key, hash| hash[key] = true }

另一个

> Hash[arr.zip Array.new(arr.size, true)]
# => {"a"=>true, "b"=>true, "c"=>true}

您也可以使用Array#product

['a', 'b', 'c'].product([true]).to_h
  #=> {"a"=>true, "b"=>true, "c"=>true}

以下代码将执行此操作:

hash = {}
['a', 'b', 'c'].each{|i| hash[i] = true}

希望这可以帮助 :)

如果切换到Python,就这么简单:

>>> l = ['a', 'b', 'c']
>>> d = dict.fromkeys(l, True)
>>> d
{'a': True, 'c': True, 'b': True}

暂无
暂无

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

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