Python:使用特定条件对嵌套列表进行排序 [英] Python: Sort a Nested List With Specific Criteria
问题描述
作为Python的初学者,我最近陷入了一个使用特定条件对嵌套列表进行排序的问题.我有一个这样的嵌套列表:
As a beginner of Python I recently get stuck for a problem of sorting a nested list with specific criteria. I have a nested list like this:
nestedList=[['R2D2','1path1','1path2'],
['R3A1','2path1','2path2'],
['R15L2','3path1','3path2']]
我希望此列表按每个嵌套列表中的第一个字符串排序.结果如下:
I would like this list to be sorted by the first string in each nested list. The result would look like:
nestedList=[['R15L2','3path1','3path2'],
['R3A1','2paht1','2path2'],
['R2D2','1path1','1path2']]
目前,我的解决方案仅使用带有反向参数的排序功能:
Currently my solution is only use the sort function with reverse parameter:
nestedList.sort(reverse=True)
我不确定这是否安全,因为我希望它也不按第二个字符串对列表进行排序.
I am not sure whether this is safe, because I would like it not sort the list also by the second string.
如何仅按第一个字符串对其进行排序? (例如"R15L2","R3A1"等)
How could I sort it only by the first string? (e.g. 'R15L2', 'R3A1', etc.)
非常感谢您的帮助!
推荐答案
您要根据键(键是列表的第一个元素)进行排序:
You want to sort according to a key (the key is the first element of a list):
nestedList.sort(key=lambda x: x[0])
或
import operator as op
nestedList.sort(key=op.itemgetter(0))
这篇关于Python:使用特定条件对嵌套列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!