用 Python 如何优雅的将 user 附加到 dept 上去?

2021-06-28 15:09:15 +08:00
 coolair

dept 结构:

[
    {
        "id": "2",
        "name": "aaa",
        "children": [
            {
                "id": "3",
                "name": "bbb",
                "children": [
                    {
                        "id": "4",
                        "name": "ccc",
                        "children": [
                        ]
                    },
                    {
                        "id": "5",
                        "name": "ddd",
                        "children": [
                        ]
                    }
                ]
            },
            {
                "id": "6",
                "name": "eee",
                "children": [
                ]
            }
        ]
    },
    {
        "id": "7",
        "name": "fff",
        "children": [
        ]
    }
]

user 数据结构:

[
    {
        "id": 2,
        "name": "aaa",
        "department": 6
    },
    {
        "id": 1,
        "name": "admin",
        "department": 7
    }
]

合并后的结构:

[
    {
        "id": "2",
        "name": "aaa",
        "children": [
            {
                "id": "3",
                "name": "bbb",
                "children": [
                    {
                        "id": "4",
                        "name": "ccc",
                        "children": [
                        ]
                    },
                    {
                        "id": "5",
                        "name": "ddd",
                        "children": [
                        ]
                    }
                ]
            },
            {
                "id": "6",
                "name": "eee",
                "children": [
                ],
                "users": [
                    {
                        "id": 2,
                        "name": "aaa"
                    },
                ]
            }
        ]
    },
    {
        "id": "7",
        "name": "fff",
        "children": [
        ],
        "users": [
            {
                "id": 1,
                "name": "admin"
            },
        ]
    }
]

我目前的做法是遍历一遍 dept 列表,找到了一个 dept 就遍历以便 user 列表,如果用户多的话,这样就很慢了…… 有什么更好的办法吗?

1376 次点击
所在节点    Python
3 条回复
dayeye2006199
2021-06-28 15:39:13 +08:00
弄个 dept -> user 的 map,是不是就快一些了
tomkliyes
2021-06-28 15:53:14 +08:00
先遍历一遍 user 得到{dept: users},再遍历 dept
lanshee
2021-06-29 10:56:55 +08:00
时间空间二选一,想要时间快就 map,空间小就 list.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/786249

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX