第二和第三个元素组成

第二和第三个元素组成

本文介绍了Groovy list.sort由第一,第二和第三个元素组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常用的列表清单,即

  list = [[2,0,1],[1,5 ,2],[1,0,3]] 

我想按照第一个元素,然后是第二个,然后是第三个元素。



期望

  assert list == [[1,0,3],[1,5,2],[2,0,1]] 

我以 list = list.sort {a,b - > a [0] => b [0]} 但只排序第一个元素。如何完成?



谢谢

解决方案

您应该可以

  list = [[2,0,1],[1,5, 2],[1,0,3]] 

list = list.sort {a,b - > a [2] => b [2]}
list = list.sort {a,b - > a [1]< => b [1]}
list = list.sort {a,b - > a [0] => b [0]}

断言列表== [[1,0,3],[1,5,2],[2,0,1]]

每个都应该覆盖前面的内容,以保持组合排序完整。

您也可以按照,当前一个相等时(并且< => / code>返回 0 ):

  list.sort {a,b  - > a [0] => b [0]?:a [1] => b [1]?:a [2] => b [2]} 


I have a groovy list of lists i.e.

list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]

I would like sort it by order of the first element, then second, then third.

Expected

assert list == [[1, 0, 3], [1, 5, 2], [2, 0, 1]]

I started with list = list.sort{ a,b -> a[0] <=> b[0] } but that only sorts the first element. How do you finish?

Thanks

解决方案

You should be able to iterate through the desired sorting in reverse order:

list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]

list = list.sort{ a,b -> a[2] <=> b[2] }
list = list.sort{ a,b -> a[1] <=> b[1] }
list = list.sort{ a,b -> a[0] <=> b[0] }

assert list == [[1, 0, 3], [1, 5, 2], [2, 0, 1]]

Each should override the previous just enough to keep the combined sorting intact.


You can also chain them in order with the Elvis operator, ?:, which will defer to the next comparison when the previous are equal (and <=> returns 0):

list.sort { a,b -> a[0] <=> b[0] ?: a[1] <=> b[1] ?: a[2] <=> b[2] }

这篇关于Groovy list.sort由第一,第二和第三个元素组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 22:12