尝试不在代码中使用太多变量,我想出了下面的代码。看起来很可怕。关于如何很好地格式化它的任何想法?我需要使用更多变量吗?
我经常编写这样的代码,并且有助于了解人们在创建较少变量时通常使用可读代码的方法
exceptions = []
# find all the distinct parent exceptions (sorted) and add to the list
# with their children list
for parent in collection.find(
{'tags': 'exception'}).sort('viewPriority').distinct('parentException'):
group_info = {'groupName': parent,
'children': [{'value': ex['value'],
'label': ex['label'],}
for ex in collection.find({'tags': 'exception',
'parentException': parent}
).sort('viewPriority')],
}
exceptions.append(group_info)
答案 0 :(得分:2)
我会把你的逻辑分解为函数
def get_children(parent):
result = collection.find({'tags': 'exception', 'parentException': parent})
result = result.sort('viewPriority')
return [{'value': ex['value'], 'label': ex['label']} for ex in result]
def get_group_info(parent):
return {'groupName': parent, 'children': get_children(parent)}
result = collection.find({'tags': 'exception'})
result = result.sort('viewPriority').distinct('parentException')
exceptions = [get_group_info(parent) for parent in result]
作为奖励,您可以轻松unittest get_children
和get_group_info
答案 1 :(得分:0)
绝对难以让这看起来有任何好处,这是我保持线路长度短并保持可读性的最佳尝试:
exceptions = []
# find all the distinct parent exceptions (sorted) and add to the list
# with their children list
for parent in (collection.find({'tags': 'exception'})
.sort('viewPriority').distinct('parentException')):
group_info = {
'groupName': parent,
'children': [{'value': ex['value'], 'label': ex['label'],}
for ex in (collection.find({'tags': 'exception',
'parentException': parent})
.sort('viewPriority'))],
}
exceptions.append(group_info)