results = []foritem in item_list:# setups# condition# processing# calculation results.append(result)
显然你对一个代码块添加了太多的责任。相反,我建议你做:
defprocess_item(item):# setups# condition# processing# calculationreturn result
results = [process_item(item) for item initem_list]
如果换成嵌套函数会如何
results = []for i in range(10):for j in range(i): results.append((i, j))
换成 List Comprehension 来实现是这样的:
results = [(i, j)for i in range(10)for j in range(i)]
如果你的代码块需要记录一些内部状态
# finding the max prior to the current itema = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]results = []current_max = 0for i in a: current_max = max(i, current_max) results.append(current_max)
# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
我们使用 generator 来实现这一点:
def max_generator(numbers): current_max = 0 for i in numbers: current_max = max(i, current_max) yield current_max