[英]How to sort a list of lists by a specific index of the inner list?
I have a list of lists.我有一份清单。 For example,例如,
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python?如果我想通过内部列表的字符串字段对外部列表进行排序,你会如何在 python 中做到这一点?
This is a job for itemgetter这是itemgetter的工作
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
It is also possible to use a lambda function here, however the lambda function is slower in this simple case也可以在此处使用 lambda 函数,但是在这种简单情况下,lambda 函数会较慢
in place到位
>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])
not in place using sorted:未使用排序:
>>> sorted(l, key=lambda x: x[2])
Itemgetter 允许您按多个条件/列进行排序:
sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))
也可以通过 lambda 函数实现多个条件
sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))
array.sort(key = lambda x:x[1])
您可以使用此代码段轻松排序,其中 1 是元素的索引。
Like this:像这样:
import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
I think lambda function can solve your problem.我认为 lambda 函数可以解决您的问题。
old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])
#Resulst of new_list will be:
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
More easy to understand (What is Lambda actually doing):更容易理解(Lambda 实际在做什么):
ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
#return the third item of the list
return ls[2]
#Sort according to what the thirdItem function return
ls2.sort(key=thirdItem)
**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])**
correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list?如果我错了,请纠正我,但“x[2]”不是调用列表中的第 3 项,而不是调用嵌套列表中的第 3 项? should it be x[2][2]?应该是 x[2][2] 吗?
Sorting a Multidimensional Array execute here在此处执行对多维数组进行排序
arr=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]
arr.sort(key=lambda x:x[0])
la=set([i[0] for i in Points])
for i in la:
tempres=list()
for j in arr:
if j[0]==i:
tempres.append(j[1])
for j in sorted(tempres,reverse=True):
print(i,j)
Make sure that you do not have any null or NaN values in the list you want to sort.确保要排序的列表中没有任何 null 或 NaN 值。 If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.如果有 NaN 值,那么您的排序将关闭,影响非空值的排序。
Check out Python: sort function breaks in the presence of nan查看Python:排序函数在 nan 存在的情况下中断
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.