简体   繁体   English

如何在Python 3中仅对嵌套列表中的子列表的某些元素进行排序

[英]How to sort only some elements of a sublist from a nested list in Python 3

I have a nested list. 我有一个嵌套列表。 For example: 例如:

data=[['Alan', 8, 4, 5], ['Jog', 10, 1, 2], ['Rhys', 7, 8, 8], ['Sam', 7, 8, 9], ['Tom', 5, 6, 9], ['Tommo', 5, 4, 6]]

Now I want to sort the numbers within the sub-lists into descending order and finally arrange the nested list into alphabetical order in Python 3. 现在,我想将子列表中的数字降序排列,最后在Python 3中将嵌套列表按字母顺序排列。

So output data should be: 因此输出数据应为:

[['Alan', 8, 5, 4], ['Jog', 10, 2, 1], ['Rhys', 8, 8, 7], ['Sam', 9, 8, 7], ['Tom', 9, 6, 5], ['Tommo', 6, 5, 4]]

where numbers in Rhys, Sam, Tom and Tommo have been reordered into descending order. Rhys,Sam,Tom和Tommo中的数字已重新排序为降序。

您可以使用列表推导:

[[list[0]] + sorted(list[1:], reverse=True) for list in sorted(data)]

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

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