1

我有一个这样的对象,并希望在每个维度(简化的 json)中按时间(第一行,第二个点)对其进行排序:

[{
    "type":"point"
},
{
    "type":"line",
    "children": [
        {
            "type":"point"
        },
        {
            "type":"point"
        },
        {
            "type":"line"
        }
    ]

},
{
    "type":"point"     
}]

这个维度可能更深,并且彼此之间有更多的点/线。

排序后的输出将是这样的:

[{
    "type":"line",
    "children": [
        {
            "type":"line"
        },
        {
            "type":"point"
        },
        {
            "type":"point"
        }
    ]

},
{
    "type":"point"
},
{
    "type":"point"     
}]

谢谢

4

1 回答 1

2

您需要递归处理:

from operator import itemgetter

def sortLinesPoints(data):
    if isinstance(data, dict):
        if 'children' in data:
            sortLinesPoints(data['children'])
    else:
        for elem in data:
            sortLinesPoints(elem)
        data.sort(key=itemgetter('type'))
于 2013-03-30T15:00:28.743 回答