简体   繁体   English

Ruby:匹配维度数组中的first,second,this等元素

[英]Ruby: match first, second, this etc elements from a dimensional array

I have an array of arrays. 我有一个数组数组。 I want to concatenate the first, second, third elements of arrays. 我想连接数组的第一,第二,第三元素。

Example arrays: 数组示例:

a =  [[4, 5, 6], [1, 2, 3], [8, 9, 10]]
a1 = [[1, 2, 3], [8, 9, 10]]
a2 = [[4, 5, 6], [1, 2, 3], [8, 9, 10], [11, 21, 31]]

Output: 输出:

out of a:  [[4,1,8],[5,2,9],[6,3,10]]
out of a1: [[1,8],[2,9],[3,10]]
out of a2: [[4,1,8,11],[5,2,9,21],[6,3,10,31]]

Use transpose method 使用transpose方法

a.transpose
 => [[4, 1, 8], [5, 2, 9], [6, 3, 10]] 

Array# transpose : Array# transpose

[a, a1, a2].map(&:transpose)
# [
#   [[4, 1, 8], [5, 2, 9], [6, 3, 10]],
#   [[1, 8], [2, 9], [3, 10]],
#   [[4, 1, 8, 11], [5, 2, 9, 21], [6, 3, 10, 31]]
# ]

Whenever Array#transpose can be used so can Enumerable#zip . 只要可以使用Array#transpose就可以使用Enumerable#zip

a.first.zip *a.drop(1)
  #=> [[4,1,8],[5,2,9],[6,3,10]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ruby将第一个数组中的元素与第二个数组进行匹配 - Ruby match elements from the first with second array 将元素从第一个数组添加到第二个数组 - Adding elements from first array to second array 我如何 output 数组中的第一个、最后一个、第二个、倒数第二个等元素? - How do I output the first, the last, the second, the second to last etc elements in an array? 从数组1的第一个元素,数组2的第一个元素,数组1的第二个元素,数组2的第二个元素等创建python数组 - Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc 查找与第二个数组的元素匹配的数组元素 - Finding elements of an array that match elements of a second array 如何按第一个字母然后第二个字母等对数组中的元素进行排序? - how do I sort elements within an array by first alphabet then second alphabet etc? 删除第一个数组中与第二个数组中的元素匹配的所有子字符串 - Remove all substrings in first-array that match elements in second-array Ruby:将gsub应用于第一和第二个数组项 - Ruby: Apply gsub to first and second array items 如何根据第二列对二维数组中的第一列进行排序? - How to sort the first column in a 2-dimensional array based on the second? 我如何从第二个数组中找到内部键和值与第一个数组匹配的数组键? - How can I find the array key from second array where the inner keys and values match first array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM