python字典dict clear()清空键值对

字典clear()方法

前面的章节中介绍了列表list的clear()方法,在python的字典类当中,也内置了类实例的方法clear(),可以用于清空字典中的键值对。


字典clear()语法及参数

dict.clear()

python字典的clear()方法不接收任何参数,如果传递了,python会抛出TypeError。


字典clear()返回值

clear()方法无返回值,但可以清空调用对象的键值对。


字典clear()方法实例代码

>>> d = {'web':'x1y1z1.com','name':'笨鸟工具'}
>>> type(d)

>>> d.clear()
>>> d
{}
>>> type(d)

>>> d.clear(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: clear() takes no arguments (1 given)

实例代码解析

如上代码,当尝试给字典dict的clear()方法传递一个参数时,python抛出TypeError,并提示:clear() takes no arguments (1 given),即字典dict的clear()方法不需要参数。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.