问题描述
带注释的代码:
result = {}
def number_of_products():
return 1 # 2,3...n
def total_inventory():
return 100 # 200,300... n
def set_values():
result["numberOfProducts"] = number_of_products()
result["totalInventory"] = total_inventory()
def run_orders():
results = []
for i in range(4):
set_values()
# result = {'numberOfProducts': 1,'totalInventory': 1000} for the first iteration
# result = {'numberOfProducts': 2,'totalInventory': 2000} for the first iteration
...
# Add result to the array for future use.
results.append(result)
# Clean up the dictionary for reuse.
result.clear()
print(results)
# Expectation
# [{'numberOfProducts': 1,'totalInventory': 1000},{'numberOfProducts': 2,'totalInventory': 2000},...]
# Actual
# [{},{},...]
run_orders()
如您所见,当我使用 .clear()
方法时,数组中出现空值。
我也尝试使用 result = {}
但结果如下:
[{'numberOfProducts': 1,{'numberOfProducts': 1,...]
如何保留从不同结果中获得的值?
解决方法
使用全局 dict 的理由真的为零,只需为每个结果创建一个新的 dict。事实上,“set_values
”可能应该返回一个新的字典:
def number_of_products():
return 1 # 2,3...n
def total_inventory():
return 100 # 200,300... n
def get_values():
return {
"numberOfProducts": number_of_products(),"totalInventory": total_inventory()
}
def run_orders():
results = []
for _ in range(4):
result = get_values()
results.append(result)
print(results)
run_orders()