我找到了关于如何对列表列表进行排序的问题,但我的问题是我的内部列表有不同的长度,我想根据内部列表的最后一项对它们进行排序。
例如,我有一个列表:
[ [1, 2, 3], [2, 4] ]我想根据内部列表中的最后一项对它们进行排序,即“3”和“4”。
那么,有一个很好的方法吗?
谢谢回复。
I found the question about how to sort a list of list, but my problem is that my inner lists have different length and I want to sort them based on the last item of my inner list.
For example, I have a list:
[ [1, 2, 3], [2, 4] ]And I want to sort them based on the last item in my inner list, i.e. "3" and "4".
So, is there a good way to do this?
Thanks for the reply.
最满意答案
看看python内置的排序函数。
>>> sorted(a, key=lambda x: x[-1]) [[1, 2, 3], [2, 4]] >>> sorted(a, key=lambda x: x[-1], reverse=True) # reverse verstin [[2, 4], [1, 2, 3]]Take a look at python built-in sorted function.
>>> sorted(a, key=lambda x: x[-1]) [[1, 2, 3], [2, 4]] >>> sorted(a, key=lambda x: x[-1], reverse=True) # reverse verstin [[2, 4], [1, 2, 3]]Python:排序列表,其中内部列表具有不同的长度?(Python: Sort a list of list where inner list with different length?)我找到了关于如何对列表列表进行排序的问题,但我的问题是我的内部列表有不同的长度,我想根据内部列表的最后一项对它们进行排序。
例如,我有一个列表:
[ [1, 2, 3], [2, 4] ]我想根据内部列表中的最后一项对它们进行排序,即“3”和“4”。
那么,有一个很好的方法吗?
谢谢回复。
I found the question about how to sort a list of list, but my problem is that my inner lists have different length and I want to sort them based on the last item of my inner list.
For example, I have a list:
[ [1, 2, 3], [2, 4] ]And I want to sort them based on the last item in my inner list, i.e. "3" and "4".
So, is there a good way to do this?
Thanks for the reply.
最满意答案
看看python内置的排序函数。
>>> sorted(a, key=lambda x: x[-1]) [[1, 2, 3], [2, 4]] >>> sorted(a, key=lambda x: x[-1], reverse=True) # reverse verstin [[2, 4], [1, 2, 3]]Take a look at python built-in sorted function.
>>> sorted(a, key=lambda x: x[-1]) [[1, 2, 3], [2, 4]] >>> sorted(a, key=lambda x: x[-1], reverse=True) # reverse verstin [[2, 4], [1, 2, 3]]
发布评论