Ruby:反转哈希以保留非唯一值 [英] Ruby: Invert a hash to also preserve non unique values
本文介绍了Ruby:反转哈希以保留非唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{a=> [1,2,3],b=> [4,5,6],c=> [3,4,5],d=> [7,2,3]}
我想要做的是对所有现有的值与包含它的所有键的数组,例如将上面的内容转换为:
{1 => [a],2 => [a,d],3 => [a,c,d],4 => [b,c]}
解决方案
I更喜欢@ Jikku的解决方案,但总有另一种方式。这是一个。
代码
def inside_out(h)
g = h.flat_map {| s,a | a.product([s])}
.group_by(&:first)
g.merge(g){| _,a | a.map(& lt; last)}
end
strong>
h = {a=> [1,2,3],b=> [4,5,6],c=> [3,4,5],d=> [7,2,3]}
inside_out(h)
#=> {1 => [a],2 => [a,d],3 => [a,c,d],4 => [b ,c],
#5 => [b,c],6 => [b],7 => [d]}
说明
code> h 以上:
a = h.flat_map {| s,a | a.product([s])}
#=> [[1,a],[2,a],[3,a],[4,b],[5,b],[6,b],
#[3,c],[4,c],[5,c],[7,d],[2,d],[3, ]]
g = a.group_by(&第一个)
#=> {1 => [[1,a]],2 = [[2,a],[2,d]],
#3 => [[ a],[3,c],[3,d]],
#4 => [[4,b],[4,c]],
#5 => [[5,b],[5,c]],
#6 => [[6,b]],
# 7 => [[7,d]]}
g.merge(g){| _,a | a.map(&; last)}
#=> {1 => [a],2 => [a,d],3 => [a,c,d],4 => [b ,c],
#5 => [b,c],6 => [b],7 => [d]}
I have a hash that looks like this:
{"a" => [1, 2, 3], "b" => [4, 5, 6], "c" => [3, 4, 5], "d" => [7, 2, 3]}
What I want to do is to make a hash of all existing values with an array of all keys that included it, e.g. turn the above into this:
{1 => ["a"], 2 => ["a", "d"], 3 => ["a", "c", "d"], 4 => ["b", "c"]}
解决方案
I do prefer @Jikku's solution, but there's always another way. Here's one. [Edit: I see this is very close to @Chris's solution. I will leave it for the last line, which is a little different.]
Code
def inside_out(h)
g = h.flat_map { |s,a| a.product([s]) }
.group_by(&:first)
g.merge(g) { |_,a| a.map(&:last) }
end
Example
h = {"a" => [1, 2, 3], "b" => [4, 5, 6], "c" => [3, 4, 5], "d" => [7, 2, 3]}
inside_out(h)
#=> {1=>["a"], 2=>["a", "d"], 3=>["a", "c", "d"], 4=>["b", "c"],
# 5=>["b", "c"], 6=>["b"], 7=>["d"]}
Explanation
For h
above:
a = h.flat_map { |s,a| a.product([s]) }
#=> [[1, "a"], [2, "a"], [3, "a"], [4, "b"], [5, "b"], [6, "b"],
# [3, "c"], [4, "c"], [5, "c"], [7, "d"], [2, "d"], [3, "d"]]
g = a.group_by(&:first)
#=> {1=>[[1, "a"]], 2=>[[2, "a"], [2, "d"]],
# 3=>[[3, "a"], [3, "c"], [3, "d"]],
# 4=>[[4, "b"], [4, "c"]],
# 5=>[[5, "b"], [5, "c"]],
# 6=>[[6, "b"]],
# 7=>[[7, "d"]]}
g.merge(g) { |_,a| a.map(&:last) }
#=> {1=>["a"], 2=>["a", "d"], 3=>["a", "c", "d"], 4=>["b", "c"],
# 5=>["b", "c"], 6=>["b"], 7=>["d"]}
这篇关于Ruby:反转哈希以保留非唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文