3

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

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

有人知道函数吗?

4

5 回答 5

12

operator.itemgetter("parent_count")用作key参数list.sort():_

from operator import itemgetter
my_list.sort(key=itemgetter("parent_count"))
于 2012-07-27T10:18:57.297 回答
2

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

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}]
于 2012-07-27T10:28:22.477 回答
1

你真的有“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')
于 2012-07-27T10:23:49.620 回答
0
my_list.sort(key=lambda x:x["parent_count"])
于 2012-07-27T10:21:27.607 回答
0

你也可以这样做:

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

如果密钥不存在,则不需要operator.itemgetter并且不会导致错误(那些没有密钥的人放在开头)。

于 2012-07-27T10:22:12.830 回答