python - 在 python 中对嵌套列表进行排序会导致 TypeError
问题描述
我有下面的嵌套列表(列表列表)称为row_list
:
[
[
{
'text': 'Something',
'x0': Decimal('223.560')
},
{
'text': 'else',
'x0': Decimal('350')
},
{
'text': 'should',
'x0': Decimal('373.736')
},
{
'text': 'be',
'x0': Decimal('21.600')
}
],
[
{
'text': 'here',
'x0': Decimal('21.600')
}
]
]
我正在尝试x0
按键对所有内部列表进行排序:
row_list = sorted(row_list, key=lambda x:x['x0'])
但是,上面给了我错误:
TypeError:列表索引必须是整数或切片,而不是 str
我也尝试过使用itemgetter
:
row_list = sorted(row_list, key=itemgetter('x0'))
但这给了我同样的错误。
我究竟做错了什么?
解决方案
你有一个嵌套列表。如果你想创建一个新列表:
row_list = [list(sorted(item, key=lambda x: x["x0"])) for item in row_list]
产生
[[{'text': 'be', 'x0': Decimal('21.600')},
{'text': 'Something', 'x0': Decimal('223.560')},
{'text': 'else', 'x0': Decimal('350')},
{'text': 'should', 'x0': Decimal('373.736')}],
[{'text': 'here', 'x0': Decimal('21.600')}]]
如果您想保留原始列表,您也可以内联排序而不是创建新列表:
for sublist in row_list:
sublist.sort(key=lambda x: x["x0"])
推荐阅读
- sql-server - 使用 XmlWriter 从 LINQ 创建大型文档到 SQL / LINQPad 抛出内存不足异常
- django - 在views.py的createview中保存外键实例
- javascript - 未捕获的 ReferenceError:regeneratorRuntime 未定义导入 VFacebookLogin
- postgresql - PostgreSQL 错误:列“收入”指定了多次
- c++ - 为什么 SSL_CONNECT 在 Linux 上阻塞?
- python - 代码不能从第二个 if 语句开始工作?
- java - JFreeChart - RangeAxis 自动量程并且不从 0 开始
- r - for循环中的变量没有在R中分配
- java - 如果我加入终止(死)线程怎么办
- reactjs - 我想将 IronSource 广告网络与我的 react native 项目集成