gpt4 book ai didi

arrays - 按索引映射两个数组

转载 作者:行者123 更新时间:2023-12-02 16:03:44 25 4
gpt4 key购买 nike

我有以下数组:

arr1 = [1, 2, 3, 4]
arr2 = ['a', 'b', 'a', 'c']

我想要以下输出:

{'a' => [1, 3], 'b'=> [2], 'c' => [4]}

在 Ruby 中是否有一种快捷的方法可以做到这一点?目前,我正在使用循环和索引来创建哈希。

最佳答案

假设你的意思是

arr1 = [1, 2, 3, 4]
arr2 = %w[a b a c] # ["a", "b", "a", "d"]

所以你的第二个数组是一个字符串数组而不是变量


您可以使用 group_bywith_index枚举器指向您的变量索引并使用第二个数组对其进行分组

arr1.group_by.with_index { |_, index| arr2[index] }

关于arrays - 按索引映射两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69997283/

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