Sons classification and unlimited categories

A: father and son Category

'' ' 
Sons classification results
Beijing 0 1 2- Haidian 1 4 - sb Town 2 - Changping 3 Shanghai 0 - Qingpu - Xu Jing Town - Minhang '''

data_dict = [ {"category_id": 1, "name": "北京", "parent_id": 0}, {"category_id": 2, "name": "上海", "parent_id": 0}, {"category_id": 3, "name": "沙河", "parent_id": 1}, {"category_id": 4, "name": "sb镇", "parent_id": 3}, {"category_id": 5, "name": "昌平", "parent_id": 1}, {"category_id": 6, "name": "青浦", "parent_id": 2}, ] res_list = [] def func(data_list, parent_id=0, level=0, is_clear=True): ''' : Param data_list: the need to sort data : Param parent_id: self-association of the parent id belongs to a parent class default 0 : Param level: to display the sort of level of the first level default 0 :return: '' ' IF is_clear: # prevented per each cycle there is data remaining previous res_list.clear () for Data in DATA_LIST: # cycle the print data acquired # First determines the parent class is not IF Data [ ' the parent_id ' ] == the parent_id: # If a parent class hierarchy displayed as a first stage Data [ ' Level ' ] = Level # of data added to the dictionary of the cycle res_list.append(data) # Cycle of the second layer .. # a second layer on a layer must be 1 but parent_id + disordered but which belongs to a category certainly FUNC (DATA_LIST, Level = Level + 1, parent_id = Data [ ' category_id ' ] , is_clear = False) return res_list res = func(data_dict) for i in res: print("-" * i['level'] + i['name'])

Two: unlimited categories

def func1(data_list):
    res_data = []   # is defined to return a list of all data stored in the list 
    Tree} = {    # unlimited classification like a tree as a root root node there are many similar fulcrum dictionary 
    for I in DATA_LIST:
        Tree [I [ ' category_id ' ]] = I    # data to add id as loop mark recording 
    for Data in DATA_LIST:
         # judgment is not the root node 
        IF  Not Data [ ' the parent_id ' ]:
             # If it is not the root node is added under a category node 
            res_data.append (Tree [Data [ ' category_id ' ]])
         the else :
             # If the root node is determined whether there is a child node 
            IF  " Children "  Not  in Tree [Data [ ' the parent_id ' ]]:   #If the child node does not add child 
                Tree [Data [ ' the parent_id ' ]] [ ' Children ' ] = []    # add child node 
            Tree [Data [ ' the parent_id ' ]] [ ' Children ' ] .append (Tree [Data [ ' category_id ' ]])   # will be added to the child nodes a category 
    return res_data 
the PS: data referring to the parent-child class are classified in the data_dict

 

Guess you like

Origin www.cnblogs.com/SR-Program/p/11909274.html