Created
December 25, 2015 01:19
-
-
Save gt11799/22bcc05b626f82948d93 to your computer and use it in GitHub Desktop.
category_iteration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = [ | |
{ | |
"id": 1, | |
"parent_id": None, | |
}, | |
{ | |
"id": 2, | |
"parent_id": None, | |
}, | |
{ | |
"id": 3, | |
"parent_id": 1, | |
}, | |
{ | |
"id": 4, | |
"parent_id": 2, | |
}, | |
{ | |
"id": 5, | |
"parent_id": 1, | |
}, | |
{ | |
"id": 6, | |
"parent_id": 3, | |
}, | |
{ | |
"id": 7, | |
"parent_id": 6, | |
}, | |
{ | |
"id": 8, | |
"parent_id": 3, | |
}, | |
] | |
def the_iter(parent_id, children): | |
for item in data: | |
if item['parent_id'] == parent_id: | |
item['children'] = [] | |
children.append(item) | |
for item in children: | |
return the_iter(item['id'], item['children']) | |
if __name__ == '__main__': | |
result = [] | |
the_iter(None, result) | |
print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment