我刚刚遇到以下代码,它工作正常,但对我来说似乎很奇怪,因为它甚至不是一个闭包,我想知道它是否是就性能或最佳实践而言的正确编码方式,或者这一切都应该是替换为包含所有逻辑的常规 for 循环?
mylist = [
{'one': 20,
'two': 4},
{'one': -6,
'two': 64},
{'one': 18,
'two': 1},
{'one': 16,
'two': 100},
# ...
]
def business_function(a_list):
def compute_function(row):
"""
suppose some more complex computations + appending extra values
than this dummy example
"""
row['total'] = row['one'] + row['two']
return row
def filter_function(item):
"""
suppose some complex logic here
"""
return item['one'] > 5
# suppose there is some code here ...
filtered_list = [compute_function(item) for item in a_list if filter_function(item)]
# and some more code here ...
return filtered_list
print business_function(mylist)