Python implements a method for solving all the subitems of the current data

assume that the data structure looks like this:
there are multiple pieces of data, each with an attribute parent (pointing to its own unique identifier id of the parent id), to which it belongs).

class data
    parent
    id

when I take out one of the pieces of data, I calculate all the subordinate data in one way. Just like the data of China"s administrative region, when I get it in Guangdong Province, I will get it at the city and county level below, and if there are any grades below the county level, I will also get it at the same time.

I wrote some code, which is so ugly that it seems to use recursion. Do you have any good ideas?

Apr.05,2021

if the storage space is large enough, you can set up a dictionary
if your data is a list named CN (all provinces, cities and counties in China)

parent_d = {}
for item in CN:
    parent = item['parent']
    if parent in parent_d:
        parent_d[parent].append(item['id'])
    else:
        parent_d[parent] = [item['id']]

then traverse

def get_all_children(city_id, parent_d):
    if city_id not in parent_d or not city_id:
        return []
    result = []
    temp_parent = [city_id]
    while temp:
        cur_id = temp_parent.pop(-1)
        result += parent_d[cur_id]
        temp_parent = parent_d[cur_id] + temp_parent
    return result

post all the examples


this problem can be converted into N-tree traversal, calculating all the children of a node.

    def return_all_children(self):
        """
        
        :return:
        """
        root = self
        if not root:
            return []
        que = []  -sharp 
        res = []  -sharp 
        que.append(root)  -sharp
        while len(que):  -sharp 
            length = len(que)
            sub = []  -sharp 
            for i in range(length):
                current = que.pop(0)  -sharp 
                print(current)
                sub.append(current)
                for child in current.return_children:  -sharp 
                    que.append(child)
            res.append(sub)  -sharp 
        return res
Menu