首页 > 解决方案 > 在 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'))

但这给了我同样的错误。

我究竟做错了什么?

标签: pythonpython-3.x

解决方案


你有一个嵌套列表。如果你想创建一个新列表:

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"])

推荐阅读