簡體   English   中英

如何使用python對對象列表進行排序?

[英]How to sort a list of objects with python?

我有一個對象列表如下所示:

[{'id': 17L,
  'price': 0,
  'parent_count': 2},
 {'id': 39L,
  'price': 0,
  'parent_count': 1},
 {'id': 26L,
  'price': 2.0,
  'parent_count': 4},
 {'id': 25L,
  'price': 2.0,
  'parent_count': 3}]

我想通過'parent_count'對對象進行排序,看起來像這樣:

 [{'id': 39L,
   'price': 0,
   'parent_count': 1},
  {'id': 17L,
   'price': 0,
   'parent_count': 2},
  {'id': 25L,
   'price': 2.0,
   'parent_count': 3},
  {'id': 26L,
   'price': 2.0,
   'parent_count': 4}]

有誰知道一個功能?

使用operator.itemgetter("parent_count")作為list.sort() key參數:

from operator import itemgetter
my_list.sort(key=itemgetter("parent_count"))

你真的有“parent_say” “parent_count”嗎?

def get_parent(item):
    return item.get('parent_count', item['parent_say'])
    # return item.get('parent_count', item.get('parent_say')) if missing keys should just go to the front and not cause an exception

my_list.sort(key=get_parent)

或者更通用一點

def keygetter(obj, *keys, **kwargs):
    sentinel = object()
    default = kwargs.get('default', sentinel)
    for key in keys:
        value = obj.get(key, sentinel)
        if value is not sentinel:
            return value
    if default is not sentinel:
        return default
    raise KeyError('No matching key found and no default specified')
my_list.sort(key=lambda x:x["parent_count"])

你也可以這樣做:

my_list.sort(key=lambda x: x.get('parent_count'))

這不需要operator.itemgetter ,並且如果密鑰不存在則不會導致錯誤(那些沒有密鑰的密鑰在開始時被放置)。

此外,您可以使用此方法:

a = [{'id': 17L, 'price': 0, 'parent_count': 2}, {'id': 18L, 'price': 3, 'parent_count': 1}, {'id': 39L, 'price': 1, 'parent_count': 4}]
sorted(a, key=lambda o: o['parent_count'])

結果:

[{'parent_count': 1, 'price': 3, 'id': 18L}, {'parent_count': 2, 'price': 0, 'id': 17L}, {'parent_count': 4, 'price': 1, 'id': 39L}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM