【问题标题】:In Python, how do I sort an array of JSON objects by a value in each object?在 Python 中,如何按每个对象中的值对 JSON 对象数组进行排序?
【发布时间】:2020-01-02 23:37:05
【问题描述】:

我正在使用 Python 3.7。我有一组 JSON 对象。我想根据每个 JOSN 对象中的一个值(“分数”)对对象数组进行排序。我无法弄清楚如何编写排序函数。我试过这个

>>> arr = [{'score': 10, 'name': 'Bob'}, {'score': 15, 'name':'Susan'}, {'score': 1, 'name': 'Skippy'}]
>>> arr
[{'score': 10, 'name': 'Bob'}, {'score': 15, 'name': 'Susan'}, {'score': 1, 'name': 'Skippy'}]
>>> arr.sort(key=json['score'], reverse=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'json' is not defined
>>> arr.sort(key=json['score'], reverse=True)

但我不知道如何从排序函数的“关键”部分引用 JSON 对象。

【问题讨论】:

    标签: arrays json python-3.x sorting


    【解决方案1】:

    使用lambda 函数(带有名为json 或其他名称的参数):

    arr.sort(key = lambda json: json['score'], reverse=True)
    

    或者,operator.itemgetter

    from operator import itemgetter
    
    arr.sort(key = itemgetter('score'), reverse=True)
    

    【讨论】:

      【解决方案2】:

      您可以使用sorted(iterable, key)itemgetter,如下所示:

      >>> from operator import itemgetter
      >>> arr = [{'score': 10, 'name': 'Bob'}, {'score': 15, 'name':'Susan'}, {'score': 1, 'name': 'Skippy'}]
      >>> sorted(arr, key=itemgetter('score'), reverse=True)
      [{'score': 15, 'name': 'Susan'}, {'score': 10, 'name': 'Bob'}, {'score': 1, 'name': 'Skippy'}]
      

      itemgetter('score') 允许sorted 访问字典列表中每个字典的key 元素并相应地对列表进行排序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 2012-12-24
        相关资源
        最近更新 更多