如何使用python对对象列表进行排序?

如何使用python对对象列表进行排序?,python,list,sorting,dictionary,Python,List,Sorting,Dictionary,我有一个如下所示的对象列表: [{'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\u count'对对象进行排序,以便如下所示:

我有一个如下所示的对象列表:

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

有人知道函数吗?

使用
操作符.itemgetter(“父项计数”)
作为
参数到
列表.sort()

从操作员导入itemgetter
my_list.sort(key=itemgetter(“父项计数”))
您还可以执行以下操作:

my_list.sort(key=lambda x: x.get('parent_count'))
它不需要
操作符.itemgetter
,如果密钥不存在也不会导致错误(没有密钥的会放在开始处)。

您是否真的有“parent_say”和“parent_count”

或更一般一点

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')

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

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}]

“父项计数”是可选键吗?上面的第一个对象是“parent_say”,而不是“parent_count”?我已经编辑了这个问题。对不起,我写错了。没有“parent\u say”键。这将在使用“parent\u say”代替“parent\u count”的对象上引发一个
KeyError
。如果“parent\u count”是可选的,
itemgetter()
将需要替换为可调用项,该可调用项将返回一个合适的默认值,而不是引发KeyError。@RobCowie:我现在假设这是一个打字错误–让我们等待OP的说法。@RobCowie如果是,则它是一个一致的打字错误(在源数据和输出数据中)对不起,伙计,我写错了。它们都是“家长计数”。没有“家长说”。@ErenSüleymanoğlu:Python中的所有变异方法也是如此。它对列表进行就地排序。@ErenSüleymanoğlu它是就地排序。如果需要排序副本,请使用具有相同参数的
sorted
内置项(但将列表
my_list
作为第一个参数)
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}]