我的数据结构看起来像这样(树):
[{'children': [{'children': [{'id',*}, {'id',*}, *], * }, *] },{'children': [], *}, {*}]
我想从中提取id的提取列表。我这是非常基本的方式:
l = []
for i in some_tree:
for j in i['children']:
for k in j['children']:
l.append(k['id'])
我该怎么做:
a)在算法效率方面更好
b)更多pythonic,例如列表推导,还是像zip这样的额外技巧?答案 0 :(得分:0)
您可以直接将其更改为列表理解,就像这样
[k['id'] for i in some_tree for j in i['children'] for k in j['children']]
如果你想要更多惯用的
from operator import itemgetter
children = itemgetter("children")
[k['id'] for i in some_tree for j in children(i) for k in children(j)]