带注释的代码:
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, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, ...]
我如何持久化从不同结果中获得的值?
实际上没有理由使用全局字典,只需为每个结果创建一个新字典即可。事实上,"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()