简体   繁体   English

使用python排序功能?

[英]Using the python sorted function?

I am using the Python sorted function in order to sort a multidimensional list which has many entries. 我正在使用Python排序功能,以便对包含许多条目的多维列表进行排序。

Example: 例:

sorted_list = sorted(list_not_sorted, key=lambda x:x[1], reverse=True)

Is there a way to sort it based on the size of the numbers? 有没有一种方法可以根据数字的大小对其进行排序?

Lets say I have the following list: 可以说我有以下列表:

[
[John,973],
[Jim,99],
[Jason,912345]
]

Using that code will sort it like this: 使用该代码将对它进行如下排序:

[
[Jim,99],
[John,973]
[Jason,912345],
]

However I want it sorted like this: 但是我希望它排序如下:

[
[Jason,912345],
[John,973]
[Jim,99],
]

Is there any way to do this with this function? 有什么办法可以做到这一点?

Question has been edited for clarity! 为清楚起见,已对问题进行了编辑!

So close! 很近!

sorted_list = sorted(list_not_sorted, key=lambda x:x[1], reverse=True)

x[2] is out of bounds (as your inner lists only have 2 items, and this is accessing the third). x[2]超出范围(因为您的内部列表只有2个项目,并且正在访问第三个项目)。 Since you want to key off the number, you want x[1] . 由于要取消编号,因此需要x[1]

>>> data = [['John', 973], ['Jim', 99], ['Jason', 912345]]
>>>
>>> sorted(data, key=lambda x:x[1], reverse=True)
[['Jason', 912345], ['John', 973], ['Jim', 99]]

You don't need to create a copy of your data using sorted . 您无需使用sorted创建数据副本。 sort is enough. sort就足够了。

>>> l
[['John', 973], ['Jim', 99], ['Jason', 912345]]
>>> l.sort(key=lambda x:x[1], reverse=True)
>>> l
[['Jason', 912345], ['John', 973], ['Jim', 99]]

If you need lexicographic order: 如果您需要字典顺序:

>>> l.sort(key=lambda x:str(x[1]), reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM