python __delitem__()方法

__delitem__()方法

python内置方法__delitem__()可以用于删除列表list、字典dict等类型的数据结构中的参数指定key的元素。


语法

__delitem__(self, key, /)

python源码中对__delitem__()方法的介绍:

    Delete self[key].

参数

参数描述
key索引值,或键值对中的键

返回值

无。但__delitem__()可以删除调用对象中的元素。


__delitem__()实例代码

>>> list1 = [1,2]
>>> list1.__delitem__(0) #调用对象为list
>>> list1
[2]
>>> tup1 = (5,6)
>>> tup1.__delitem__(1) #调用对象为tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute '__delitem__'
>>> set1 = {7,8}
>>> set1.__delitem__(0) #调用对象为set
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute '__delitem__'
>>> dict1 = {'a':1,'b':2} #调用对象为dict
>>> dict1.__delitem__('a')
>>> dict1
{'b': 2}
>>> str1 = 'abc'
>>> str1.__delitem__(2) #调用对象为str
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__delitem__'

全栈后端 / python教程 :


























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