【问题标题】:How to sort a list which holds nested lists, which further holds dictionaries. the aim is to sort the main list by a dictionary VALUE如何对包含嵌套列表的列表进行排序,该列表还包含字典。目的是按字典 VALUE 对主列表进行排序
【发布时间】:2020-07-10 19:56:25
【问题描述】:

我希望使用 itemgetter 函数对与此类似的列表进行排序。我正在尝试按字典KEY“特殊号码”按升序排列列表。 因为嵌套列表处理字典,我发现这很难完成。

from operator import itemgetter


lists = [
    [{'time': str, 'ask price': str},
     {'ticker': 'BB','Special number': 10}],
    [{'time': str , 'price': str},
     {'ticker': 'AA', 'Special number': 5}
     ]
]

我尝试使用:

gg = lists.sort(key=itemgetter((1)['special number']))

print(gg)

非常感谢!

【问题讨论】:

  • "列表将按升序排列"? “升序”是什么?
  • 列表项 1 包含 {'Special number': 5},列表项 2 包含 {'Special number': 10}

标签: python list sorting dictionary


【解决方案1】:

我认为这里没有必要使用itemgetter()。如果具有键 'Special number' 的字典始终位于列表的索引 1 中,则执行以下操作就足够了:

sorted_list = sorted(lists, key=lambda x: x[1]['Special number'])
print(sorted_list)

输出

[[{'price': <class 'str'>, 'time': <class 'str'>},
  {'Special number': 5, 'ticker': 'AA'}],
 [{'ask price': <class 'str'>, 'time': <class 'str'>},
  {'Special number': 10, 'ticker': 'BB'}]]

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多