Python,itemgetter从嵌套的元素列表中排序字典值列表

时间:2016-06-08 18:03:26

标签: python sorting

如下所示(MVCE)列表data,我想首先按x坐标排序,然后按y坐标排序。
我试过了:

import operator
data = [
    { "coords": [142, -42]},
    { "coords": [147, -42]},
    { "coords": [151, -41]},
    { "coords": [147, -41]},
    { "coords": [149, -44]},
    { "coords": [150, -41]},
    { "coords": [149, -40]},
    { "coords": [150, -42]},
    { "coords": [151, -40]}
]

k1 = operator.itemgetter("coords")
# i've also tried various combinations like
#k2 = lambda data: operator.itemgetter(data["coords"][0]),\
#                  operator.itemgetter(data["coords"][1])
# but TypeError: list indices must be integers, not str

e = []
for d in sorted(data, key=k1):
    e.append(d)
print("\n".join([str(s) for s in e]))

但这会使数据仅按X排序,但不会按Y排序。

>>> { "coords": [142, -42]}
    { "coords": [147, -42]}
    { "coords": [147, -41]}
    { "coords": [149, -44]}
    { "coords": [149, -40]}
    { "coords": [150, -42]}
    { "coords": [150, -41]}
    { "coords": [151, -41]}
    { "coords": [151, -40]}

我知道我可以将多个参数传递给itemgetter。 有没有办法在一个声明中对此进行排序?

(期望的结果)

>>> { "coords": [142, -42]}
    { "coords": [147, -41]}
    { "coords": [147, -42]}
    { "coords": [149, -40]}
    { "coords": [149, -44]}
    { "coords": [150, -41]}
    { "coords": [150, -42]}
    { "coords": [151, -40]}
    { "coords": [151, -41]}

必须将数据添加到e列表中,因为这是较大处理的一部分。

与我在此处找到的sort-list-of-dictionaries-by-another-list或类似内容不重复。大多数人都希望用dict中的两个值对字典列表进行排序,这里我想用嵌套列表中的两个值进行排序。

1 个答案:

答案 0 :(得分:3)

正确排序; -42<例如-41。

要获得您想要的顺序,您可以否定y坐标:

k1 = lambda x: (x['coords'][0], -x['coords'][1])