繁体   English   中英

字典setdefault方法如何工作?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM