gpt4 book ai didi

Ruby:从二维数组中收集所有具有匹配元素的数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:57 25 4
gpt4 key购买 nike

我有一个二维数组,看起来像

array = [["apples", 11], ["oranges", 3], ["bananas", 7], ["oranges", 4], ["apples", 6], ["oranges", 9]]

我想以某种方式收集所有匹配的字符串并对关联数组中的整数求和。例如我希望输出看起来像

totals_array = [["apples", 17], ["oranges", 16], ["bananas", 7]]

我在执行此操作方面不受限制,但想不出一种巧妙的方法来执行此操作。任何帮助,将不胜感激。

最佳答案

你可以这样做:

array = [["apples", 11], ["oranges", 3], ["bananas", 7], ["oranges", 4], ["apples", 6], ["oranges", 9]]

totals_array = array.reduce(Hash.new(0)) { |h, s| h[s[0]] += s[1]; h }.to_a

totals_array = array.each_with_object(Hash.new(0)) { |(name,count),hash| hash[name] += count }.to_a

关于Ruby:从二维数组中收集所有具有匹配元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22683932/

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