Python:使用特定条件对嵌套列表进行排序

Apl*_*usG 0 python sorting nested list

作为Python的初学者,我最近遇到了使用特定条件对嵌套列表进行排序的问题.我有一个这样的嵌套列表:

nestedList=[['R2D2','1path1','1path2'], 
            ['R3A1','2path1','2path2'],
            ['R15L2','3path1','3path2']]
Run Code Online (Sandbox Code Playgroud)

我希望这个列表按每个嵌套列表中的第一个字符串排序.结果如下:

nestedList=[['R15L2','3path1','3path2'],
            ['R3A1','2paht1','2path2'],
            ['R2D2','1path1','1path2']]
Run Code Online (Sandbox Code Playgroud)

目前我的解决方案只使用带反向参数的sort函数:

nestedList.sort(reverse=True)
Run Code Online (Sandbox Code Playgroud)

我不确定这是否安全,因为我希望它不会通过第二个字符串对列表进行排序.

我怎么能只用第一个字符串对它进行排序?(例如'R15L2','R3A1'等)

非常感谢你的帮助!

eum*_*iro 5

您希望根据键进行排序(键是列表的第一个元素):

nestedList.sort(key=lambda x: x[0])
Run Code Online (Sandbox Code Playgroud)

要么

import operator as op

nestedList.sort(key=op.itemgetter(0))
Run Code Online (Sandbox Code Playgroud)