[英]Reverse mapping an array of hash to a hash
I have an Array
that contains Hash
with only one key and value as an Array
. 我有一个Array
包含Hash
只有一个键和值作为Array
。
Eg: 例如:
a = [{1 => ["foo", "bar"]}, {2 => ["hello"]}, {3 => ["world", "bar"]}]
Now I want to create a Hash
having values of above Hash
es as key and their keys as values. 现在,我想创建一个Hash
具有上述值Hash
ES的关键和作为值的键。
Eg: (desired result) 例如:(期望的结果)
res = {"foo"=>[1], "bar"=>[1, 3], "hello"=>[2], "world"=>[3]}
I have solved this is following way: 我已经解决了这是下面的方式:
b = Hash.new { |h, k| h[k] = [] }
a.each { |hash|
hash.each { |key, vals|
vals.each { |val|
b[val] << key
}
}
}
b
# => {"foo"=>[1], "bar"=>[1, 3], "hello"=>[2], "world"=>[3]}
It works fine but there should be a better, shorter way to do this than iterating so many times. 它可以正常工作,但是应该比迭代多次更好,更短的方法。 Please suggest. 请提出建议。
One could invert keys and values and then collect elements as needed: 可以反转键和值,然后根据需要收集元素:
a = [{1 => ["foo", "bar"]}, {2 => ["hello"]}, {3 => ["world", "bar"]}]
a.map(&:invert).inject({}) { |memo,el|
el = el.flatten # hash of size 1 ⇒ array [k ⇒ v]
el.first.each { |k| (memo[k] ||= []) << el.last }
memo
}
#⇒ {
# "bar" => [
# [0] 1,
# [1] 3
# ],
# "foo" => [
# [0] 1
# ],
# "hello" => [
# [0] 2
# ],
# "world" => [
# [0] 3
# ]
# }
Hope it helps. 希望能帮助到你。
I'd use group_by
, but you need to massage your data: 我会使用group_by
,但是您需要对数据进行处理:
a.flat_map(&:to_a) # => [[1, ["foo", "bar"]], [2, ["hello"]], [3, ["world", "bar"]]]
.flat_map{|key, values| values.map{|v| [key, v]}} # => [[1, "foo"], [1, "bar"], [2, "hello"], [3, "world"], [3, "bar"]]
.group_by(&:last) # => {"foo"=>[[1, "foo"]], "bar"=>[[1, "bar"], [3, "bar"]], "hello"=>[[2, "hello"]], "world"=>[[3, "world"]]}
.map{|key, values| [key, values.map(&:first)]} # => [["foo", [1]], ["bar", [1, 3]], ["hello", [2]], ["world", [3]]]
.to_h # => {"foo"=>[1], "bar"=>[1, 3], "hello"=>[2], "world"=>[3]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.