gpt4 book ai didi

ruby - 如何在 Ruby 中合并数组中的子数组?

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

我有一个数组,为了论证,它看起来像这样:

a = [[1,100], [2,200], [3,300], [2,300]]

在这四个子数组中,我想合并第一个元素重复的任何地方。所以在上面的例子中,我想合并第二个和第四个子数组。但是,需要注意的是,如果匹配子数组中的第二个元素不同,我希望保持较高的值。

所以,我想看到这个结果:

a = [[1,100], [3,300], [2,300]]

这个小难题有点超出我的 Ruby 技能,所以我向社区寻求帮助。非常感谢任何有关如何解决此问题的指导。

谢谢

最佳答案

# Get a hash that maps the first entry of each subarray to the subarray
# requires 1.8.7+ or active_support (or facets, I think)
hash = a.group_by { |first, second| first }
# Take each entry in the hash and select the biggest entry for each unique key
hash.map {|k,v| v.max }

关于ruby - 如何在 Ruby 中合并数组中的子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1236119/

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