[英]Python Review: Why doesn't code 1 produce same result as code 2?
[英]Why "result" and "current" doesn't give the same output though they are mentioned as the same in this code?
有沒有我沒有掌握的字典屬性?
List = [1, 2, 3, 4]
result = current = {}
for n in List:
current[n] = {}
current = current[n]
print(current)
print(result)
輸出1:{}
輸出2:{1:{2:{3:{4:{}}}}}
最初在您的代碼中,您將current
和result
都指向相同的 memory 位置。 但是,在每次循環迭代中,您通過將current
指向的 memory 位置重新分配給遍歷列表的鍵的新空字典來更改它。
在循環結束時:
{1: {2: {3: {4: {}}}}}
^ ^
| |
| |
| current point here
|
result points here
因此解釋您收到的輸出
如前所述,這是一個簡單的 memory 分配問題。 Python 使用動態 memory 分配因此問題。
一個簡單的解決方法是 -
List = [1, 2, 3, 4]
result = {}
current = {}
for n in List:
current[n] = {}
current = current[n]
print(current)
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.