首页 > 解决方案 > 仅使用一列对嵌套列表进行排序

问题描述

我做了一个嵌套列表,我[[name, score]][['Ashish', 32], ['Varsha', 32], ['Nano', 31.9], ['Sparsh', 40.3], ['Ria', 30.2]]对这个列表进行排序。到数字。

a['score'].sort(reverse = True)

我尝试了上面的代码,但它给出了这个错误,

TypeError: list indices must be integers or slices, not str

我应该尝试什么?

标签: pythonpython-3.xnested-lists

解决方案


基本上是@AndreyKesley 所说的。

您的嵌套列表不是以“分数”作为一列名称的二维列表。这是一个列表列表,你不能只抓住第二列。

但是,您可以按每个元素的第二项排序:

a = [['Ashish', 32], ['Varsha', 32], ['Nano', 31.9], ['Sparsh', 40.3], ['Ria', 30.2]]

a.sort(key=lambda el: el[1], reverse=True)
print(a)

[['Sparsh', 40.3], ['Ashish', 32], ['Varsha', 32], ['Nano', 31.9], ['Ria', 30.2]]

或者不带 lambda 的更适合初学者的版本:

import operator

a = [['Ashish', 32], ['Varsha', 32], ['Nano', 31.9], ['Sparsh', 40.3], ['Ria', 30.2]]

a.sort(key=operator.itemgetter(1), reverse=True)
print(a)

推荐阅读