[英]How to sort a list of list with the first value, if the both are equal check the second and so on
If you are given a list of list (heterogenous).如果给你一个列表列表(异类)。 How do I sort it based on first value and if first value are equal then sort using the second value for those items and even if second values are equal then sort using the third value and so on.
如何根据第一个值对其进行排序,如果第一个值相等,则使用这些项目的第二个值进行排序,即使第二个值相等,然后使用第三个值进行排序,依此类推。
I know how to sort using a particular index of the inner list我知道如何使用内部列表的特定索引进行排序
Let a list be:设一个列表:
a = [[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
I want:我想:
a=[[1,2,3],[2,1,1],[2,2,2],[2,2,3],[2,2,4],[2,2,5]]
using,使用,
a = sorted(a, key = lambda x:x[0])
will sort it using the first value, but if the first value is equal then it will add the values according to values which come first.将使用第一个值对其进行排序,但如果第一个值相等,则它将根据首先出现的值添加值。
How do I go about with this?我该如何处理这个问题?
If on getting the first value equal, I wanted to sort using the last value in the inner list how would I do that?如果在使第一个值相等时,我想使用内部列表中的最后一个值进行排序,我该怎么做?
I mean the output I want is:我的意思是我想要的 output 是:
a=[[1,2,6],[2,2,1],[2,2,2],[2,2,3],[2,1,4],[2,2,5]]
How can this be done?如何才能做到这一点?
Literally it sorts with using sorted()
:从字面上看,它使用
sorted()
进行排序:
a = [[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
print(sorted(a, key=lambda a: (a[0], a[-1])))
# output - [[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]
You can create a tuple which defines the order of comparison.您可以创建一个定义比较顺序的元组。
>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: (x[0],x[2],x[1]))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]
It can also be done using tuple comprehension.也可以使用元组推导来完成。 For example, sorting only on even indexes:
例如,仅对偶数索引进行排序:
>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: tuple(x[i] for i in range(len(x)) if i%2==0))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]
The above sorting example is same as:上面的排序示例与:
>>> a=[[2,2,1],[2,2,3],[2,1,4],[2,2,5],[1,2,6],[2,2,2]]
>>> sorted(a,key=lambda x: (x[0],x[2]))
[[1, 2, 6], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 1, 4], [2, 2, 5]]
you can just use sorted(a) to sort your list of lists您可以使用 sorted(a) 对列表列表进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.