二维数组按内部元素的数量排序 [英] Sorting of 2D Array by its amount of in the inner elements

查看:69
本文介绍了二维数组按内部元素的数量排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按内部元素的长度对2D数组排序?内部元素的数量不相同.

How do I sort a 2D array by the length of its inner elements? The number of inner elements is not the same.

示例:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]

排序后,该数组将变为:

After sorting, the array will become:

#=> [[4, 5, 6, 7], [2, 3], [8, 9], [1]]

推荐答案

此解决方案有效:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by! { |array| -array.length }
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]

我正在使用 sort_by 方法并按长度从最大到最小的顺序进行排序.

I am using the sort_by method and sort by length from largest to smallest.

此解决方案更具可读性,并且可以正常工作,但速度稍慢:

This solution is more readable and works as well, but it is a bit slower:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by(&:length).reverse!
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]

我正在使用 sort_by 使用length的方法,它将按长度从最小到最大对数组进行排序.然后,我使用 reverse! 方法将其按从大到小的顺序排列.

I am using the sort_by method using length, which will sort the array from smallest to largest by length. Then I use the reverse! method it to have it in order from largest to smallest.

这篇关于二维数组按内部元素的数量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆