對于配置驗證模式,我需要有一個重復的嵌套字典。例如,假設我們有以下字典:
{
"conf1": "x",
"conf2": "x",
}
現在我想擁有一個conf3包含現有字典的鍵,以進行最大迭代次數(即 3 次)所以最終結果需要如下所示:
{
"conf1": "x",
"conf2": "x",
"conf3": {
"conf1": "x",
"conf2": "x",
"conf3": {
"conf1": "x",
"conf2": "x",
}
}
}
我試圖寫一個遞回函式,但這個解決方案conf3是無限重復的
def build_nested_configuration_schema(schema: dict, iteration: int = 0) -> dict:
iteration = 1
if iteration == 3:
return schema
schema.update({"conf3": build_nested_configuration_schema(schema, iteration)})
return schema
new_config = build_nested_configuration_schema({"conf1": "x", "conf2": "x"})
uj5u.com熱心網友回復:
根據我的評論,使用 copy 包將斷開指標參考,因為您的示例結果。
import copy
def build_nested_configuration_schema(schema: dict, iteration: int = 0) -> dict:
internal_schema = copy.copy(schema)
iteration = 1
if iteration == 3:
return internal_schema
schema.update({"conf3": build_nested_configuration_schema(internal_schema, iteration)})
return schema
new_config = build_nested_configuration_schema({"conf1": "x", "conf2": "x"})
print(new_config)
印刷
{'conf1': 'x', 'conf2': 'x', 'conf3': {'conf1': 'x', 'conf2': 'x', 'conf3': {'conf1': 'x', 'conf2': 'x'}}}
發生這種情況的主要原因是遞回,python 最終將使用方法呼叫中的值作為指向值的指標,而不是單獨的存盤值。這就是為什么您的方法確實回傳,并且沒有達到遞回最大限制的原因。conf3 的值最終是 {conf1: x, conf2: x, conf3: } 這就是為什么除錯會向你顯示一個永無止境的 conf3 值流。copy 方法將起作用,并且可能有更多 Pythonic 方法來解決該問題,但是如果運行時記憶體沒有得到嚴格管理,這將起作用。
uj5u.com熱心網友回復:
我的解決方案。由于 pypalms 正確表明我們需要制作模式的副本。
def build_nested_configuration_schema(schema: dict, iteration: int = 0) -> dict:
iteration = 1
if iteration == 3:
return schema
schema.update({"conf3": build_nested_configuration_schema(schema.copy(), iteration)})
return schema
uj5u.com熱心網友回復:
本方案使用原提供schema的模板,不需要遞回。
def build_nested_configuration_schema(schema: dict) -> dict:
maxNesting = 3
result = schema.copy()
current = result
for i in range(maxNesting - 1):
next = schema.copy()
current['conf3'] = next
current = next
return result
new_config = build_nested_configuration_schema({"conf1": "x", "conf2": "x"})
print(new_config)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404566.html
標籤:
上一篇:按順序存盤鍵值的值?
下一篇:動態迭代Python字典
