[英]How does dictionary setdefault method work?
我在python shell中執行以下操作:
a = [0, 1]
b = [2, 4]
c = [2, 0]
d = [4, 3]
e = [a, b, c, d]
neighbour_list = {}
我想嘗試以下方法:
neighbour_list.setdefault(x, [])
然后
print(neighbour_list)
版畫
{4: []}
我不明白它在做什么。 為什么python選擇x為4?
如果x
先前定義為4
則會發生這種情況。 Python必須做到這一點,而沒有“選擇定義”。
在您提供的代碼中,您沒有顯示x
定義方式,但是肯定已經定義了x
,否則您將得到NameError
:
>>> abcd_list = {}
>>> abcd_list.setdefault(x, [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x=4
>>> abcd_list.setdefault(x, [])
[]
>>> abcd_list
{4: []}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.