Python 使用dict.clear()删除所有值。如何保持dict值?
带注释的代码:Python 使用dict.clear()删除所有值。如何保持dict值?,python,python-3.x,list,dictionary,persist,Python,Python 3.x,List,Dictionary,Persist,带注释的代码: 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"] =
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}, ...]
如何持久化从不同结果中获得的值?使用全局dict的理由实际上是零,只需为每个结果创建一个新dict即可。事实上,“
set_values
”可能会返回一个新的dict:
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()
“清理字典以便重用”-不要重用同一个dict,只需创建一个新dict…!?在第二次尝试中,您应该得到UnboundLocalError。这个结果很奇怪。此外,使用全局变量通常不是一个好主意。也许你可以在这个主题中找到答案:不是真的,这里的主要问题是对全局/局部规则的误解。