简体   繁体   English

在python中对嵌套列表进行排序会导致TypeError

[英]Sorting nested lists in python results in TypeError

I have below nested list (lists of list) called row_list : 我下面有嵌套列表(列表列表),称为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')
        }
    ]
]

I am trying to sort all inner list by the x0 key: 我正在尝试通过x0键对所有内部列表进行排序:

row_list = sorted(row_list, key=lambda x:x['x0'])

However, above gives me the error: 但是,上面给我的错误:

TypeError: list indices must be integers or slices, not str TypeError:列表索引必须是整数或切片,而不是str

I've tried using itemgetter as well: 我也尝试过使用itemgetter

row_list = sorted(row_list, key=itemgetter('x0'))

But that gives me the same error. 但这给了我同样的错误。

What am I doing wrong? 我究竟做错了什么?

you have a nested list. 您有一个嵌套列表。 if you want to create a new list: 如果要创建新列表:

row_list = [list(sorted(item, key=lambda x: x["x0"])) for item in row_list]

which produces 产生

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

if you want to keep the original list you could also sort inline instead of creating a new list: 如果要保留原始列表,也可以内联排序,而不是创建新列表:

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)

output 输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM