首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python递归排序所有嵌套的可迭代对象

python递归排序所有嵌套的可迭代对象
EN

Stack Overflow用户
提问于 2018-05-30 07:04:13
回答 2查看 63关注 0票数 -4

如何递归排序一个迭代表中所有嵌套的迭代表?

例如:

代码语言:javascript
复制
d = {
    'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}],
    'x': ['c', 'b', 'a'],
    'z': {
        'a': [3, 1, 2],
        'd': [{'y': [6,5,1]}, {'w': 1}],
        'c': {'2': 2, '3': 3, '4': 4}
    },
    'w': {1:1, 2:2, 3:3}
}

我是输出,就像

代码语言:javascript
复制
{'e': [{'x': [{'1': 1, '2': 2}]}, {'y': 'y'}],
 'w': {1: 1, 2: 2, 3: 3},
 'x': ['a', 'b', 'c'],
 'z': {'a': [1, 2, 3],
       'c': {'2': 2, '3': 3, '4': 4},
       'd': [{'w': 1}, {'y': [1, 5, 6]}]}}
EN

回答 2

Stack Overflow用户

发布于 2018-05-30 07:04:47

代码语言:javascript
复制
from pprint import pprint
d = {
    'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}],
    'x': ['c', 'b', 'a'],
    'z': {
        'a': [3, 1, 2],
        'd': [{'y': [6,5,1]}, {'w': 1}],
        'c': {'2': 2, '3': 3, '4': 4}
    },
    'w': {1:1, 2:2, 3:3}
}
def rec_sort(iterable):
    """Recursively sort
    """
    def sort_dict_key(x):
        if isinstance(x, dict):
            return sorted(x.keys(), key=sort_dict_key)
        return x
    if isinstance(iterable, dict):
        d = {}
        for k, v in iterable.items():
            d[k] = rec_sort(v)
    elif isinstance(iterable, list):
        iterable.sort(key=sort_dict_key)
        for pos,item in enumerate(iterable):
            iterable[pos] = rec_sort(item)
    return iterable

pprint(rec_sort(d))
票数 2
EN

Stack Overflow用户

发布于 2018-05-30 07:13:15

您可以使用递归:

代码语言:javascript
复制
import json
d = {'x': ['c', 'b', 'a'], 'z': {'a': [3, 1, 2], 'c': {'3': 3, '2': 2, '4': 4}, 'd': [{'y': [6, 5, 1]}, {'w': 1}]}, 'e': [{'y': 'y'}, {'x': [{'1': 1, '2': 2}]}], 'w': {1: 1, 2: 2, 3: 3}}
def sort_nested(c):
   if not isinstance(c, dict):
     return sorted(c) if isinstance(c, list) else c
   return {a:sorted(sort_nested(i) for i in b) if isinstance(b, list) else sort_nested(b) for a, b in c.items()}

print(json.dumps(sort_nested(d), indent=4))

输出:

代码语言:javascript
复制
{
 "x": [
    "a", 
    "b", 
    "c"
], 
"z": {
    "a": [
        1, 
        2, 
        3
    ], 
    "c": {
        "3": 3, 
        "2": 2, 
        "4": 4
    }, 
    "d": [
        {
            "w": 1
        }, 
        {
            "y": [
                1, 
                5, 
                6
            ]
        }
    ]
}, 
"e": [
    {
        "x": [
            {
                "1": 1, 
                "2": 2
            }
        ]
    }, 
    {
        "y": "y"
    }
 ], 
  "w": {
    "1": 1, 
    "2": 2, 
    "3": 3
   }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档