如何解决使用 dict.clear() 删除所有值我怎样才能坚持字典值?
带注释的代码:
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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。