簡體   English   中英

為什么“結果”和“當前”沒有給出相同的 output 盡管它們在此代碼中被提及為相同?

[英]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:{}}}}}

最初在您的代碼中,您將currentresult都指向相同的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM