在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"])
from decimal import Decimal
l = [
    [
        {
            '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')
        }
    ]]
for i in l:
    i.sort(key=lambda x:x['x0'])
print(l)

输出

    [[{'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')}]]

相关内容

最新更新