Python列表 删除() 是Python编程语言中的一个内置函数,用于从 列表 .
null
语法:
列出你的名字。移除(obj)
参数:
- obj: 要从列表中删除的对象
返回:
该方法不返回任何值,但从列表中删除给定对象。
例外情况:
如果元素不存在,它会抛出ValueError:list。删除(x):x不在列表中例外。
注:
它会从列表中删除对象的第一个匹配项。
例1: 从列表中删除元素
Python3
# Python3 program to demonstrate the use of # remove() method # the first occurrence of 1 is removed from the list list1 = [ 1 , 2 , 1 , 1 , 4 , 5 ] list1.remove( 1 ) print (list1) # removes 'a' from list2 list2 = [ 'a' , 'b' , 'c' , 'd' ] list2.remove( 'a' ) print (list2) |
输出:
[2, 1, 1, 4, 5]['b', 'c', 'd']
例2: 删除不存在的元素
Python3
# Python3 program for the error in # remove() method # removes 'e' from list2 list2 = [ 'a' , 'b' , 'c' , 'd' ] list2.remove( 'e' ) print (list2) |
输出:
Traceback (most recent call last): File "/home/e35b642d8d5c06d24e9b31c7e7b9a7fa.py", line 8, in list2.remove('e') ValueError: list.remove(x): x not in list
例3:使用 在 L 有重复元素的
Python3
# My List list2 = [ 'a' , 'b' , 'c' , 'd' , 'd' , 'e' , 'd' ] # removing 'd' list2.remove( 'd' ) print (list2) |
输出:
['a', 'b', 'c', 'd', 'e', 'd']
笔记 :如果列表包含重复元素,则会从列表中删除对象的第一个匹配项。
示例4:给定一个列表,从列表中删除所有1并打印列表
Python3
# Python3 program for practical application # of removing 1 until all 1 are removed from the list list1 = [ 1 , 2 , 3 , 4 , 1 , 1 , 1 , 4 , 5 ] # looping till all 1's are removed while (list1.count( 1 )): list1.remove( 1 ) print (list1) |
输出:
[2, 3, 4, 4, 5]
示例5:给定一个列表,使用in关键字从列表中删除所有2
Python3
# Python3 program for practical application # of removing 2 until all 2 are removed from the list mylist = [ 1 , 2 , 3 , 2 , 2 ] # looping till all 2's are removed while 2 in mylist: mylist.remove( 2 ) print (mylist) |
输出:
[1, 3]
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END