python - 仅使用一列对嵌套列表进行排序
问题描述
我做了一个嵌套列表,我[[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
我应该尝试什么?
解决方案
基本上是@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)
推荐阅读
- angular - 'Post' 类型的参数不能分配给'string | 类型的参数 象征'
- python - Python更改JSON文件而不更新整个文件
- javascript - 如何将 html+javascrip 代码转换为 react-hook
- java - 将 JSON 字符串反序列化为包装泛型类的类
- node.js - 猫鼬填充模型嵌套在对象中
- javascript - 用户单击图像区域后更改元素的 CSS 样式
- stripe-payments - 使用 customer.subscription.update 而不是 invoice.paid 和 invoice.payment_failed 事件 webhook 来处理 Stripe 订阅
- java - 错误:不兼容的类型:推理变量 T 具有不兼容的界限
- sql - 如何使用相同的数据集更改 2 列或更多列的名称
- agora.io - Agora.io 是否提供类似 whatsapp 的通话功能?