gpt4 book ai didi

ruby - 将两个数组合并为散列时保留重复键的键值对

转载 作者:太空宇宙 更新时间:2023-11-03 17:22:20 25 4
gpt4 key购买 nike

我有两个 ruby​​ 数组:

array_one = ["farmer_joe", "farmer_judy", "farmer_crazy_eyes", "farmer_joe"]

array_two = ["pigs", "chickens", "elephants", "cows"]

如果我使用 zip 函数,我会丢失 Farmer Joe 的重复值和 key 对。

hash_one = Hash[array_one.zip array_two] 

=> {"farmer_joe"=>"cows", "farmer_judy"=>"chickens", "farmer_crazy_eyes"=>"elephants"}

理想情况下,我想要一个函数,让我可以用一种漂亮的 ruby 风格的单行方法来克服这个问题。也许像这样合并重复的键并将它们的值添加到数组中。

hash_one = Hash[array_one.super_special_zip array_two]

=> {"farmer_joe"=>["pigs","cows"], "farmer_judy"=>["chickens"], "farmer_crazy_eyes"=>["elephants"]}

有没有这样的super_special_zip方法?还是有充分的理由说明为什么这首先是一项愚蠢的差事?

最佳答案

执行此操作的标准方法有 3 种。

a1 = ["farmer_joe", "farmer_judy", "farmer_crazy_eyes", "farmer_joe"]
a2 = ["pigs", "chickens", "elephants", "cows"]
pairs = a1.zip(a2) # or [a1,a2].transpose
#=> [["farmer_joe", "pigs"], ["farmer_judy", "chickens"],
# ["farmer_crazy_eyes", "elephants"], ["farmer_joe", "cows"]]

<强>1。使用 Hash.new使用空数组的默认值创建散列

pairs.each_with_object(Hash.new { |h,k| h[k]=[] }) { |(f,l),h| h[f] << l }
# => {"farmer_joe"=>["pigs", "cows"], "farmer_judy"=>["chickens"],
# "farmer_crazy_eyes"=>["elephants"]}

这个的一个变体(往往稍微快一点)是:

pairs.each_with_object({}) { |(f,l),h| (h[f] ||= []) << l }

<强>2。使用 Hash#update 的形式(又名合并!)它需要一个 block 来确定要合并的两个哈希中存在的键的值

pairs.each_with_object({}) { |(f,l),h| h.update(f=>[l]) { |_,o,n| o+n } }
#=> {"farmer_joe"=>["pigs", "cows"], "farmer_judy"=>["chickens"],
# "farmer_crazy_eyes"=>["elephants"]}

<强>3。使用 Enumerable#group_by

h = pairs.group_by(&:first)
#=> {"farmer_joe"=>[["farmer_joe", "pigs"], ["farmer_joe", "cows"]],
# "farmer_judy"=>[["farmer_judy", "chickens"]],
# "farmer_crazy_eyes"=>[["farmer_crazy_eyes", "elephants"]]}
h.keys.each { |k| h[k] = h[k].map(&:last) }
h
#=> {"farmer_joe"=>["pigs", "cows"], "farmer_judy"=>["chickens"],
# "farmer_crazy_eyes"=>["elephants"]}

最后两行有很多替代方案,其中之一是:

h.merge(h) { |*_,v| v.map(&:last) }

关于ruby - 将两个数组合并为散列时保留重复键的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com