我有一个这样的列表:
list1 = [['art_25', 'title', 'author'], ['art_12', 'title', 'author'], ['art_4', 'title', 'author']]
我如何排序这个列表 s.t.输出等于
[['art_4', 'title', 'author'], ['art_12' ...], ['art_25', ...]] ?
感谢您的帮助!
最佳答案
您可以将 sorted
与 key
参数一起使用。您可以创建一个 lambda
表达式,在 '_'
字符上拆分,将其转换为 int
,然后按该值排序。
list1 = [['art_25', 'title', 'author'],
['art_12', 'title', 'author'],
['art_4', 'title', 'author']]
>>> sorted(list1, key=lambda i: int(i[0].split('_')[1]))
[['art_4', 'title', 'author'],
['art_12', 'title', 'author'],
['art_25', 'title', 'author']]
关于Python:按数字对列表中的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280984/