arrays - 按索引映射两个数组

标签 arrays ruby dictionary hash

我有以下数组:

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/

相关文章:

dictionary - Gradle无法在任务内部创建Groovy Map对象

python - 从 Python 字典中的项目中删除重复值

php - 复杂的合并技术 : How to transpose specific sets of data using a configuration array?

arrays - 异步访问 Firebase 中的数组

arrays - mongoDB 对嵌套对象数组的聚合查找

ruby - QtRuby 可以与 Qt 5 一起使用吗?

ruby - 如何使Searchkick/Elasticsearch where子句不区分大小写?

ruby - 为什么在 Ruby 0.0/0、3.0/0 和 3/0 中表现不同?

python - 如何将以下列表转换为字典?

javascript - 谷歌图表 :Data column(s) for axis #0 cannot be of type string error