📜  Python列表删除()

📅  最后修改于: 2022-05-13 01:54:25.122000             🧑  作者: Mango

Python列表删除()

Python List remove()是Python编程语言中的一个内置函数,用于从 List 中删除给定对象。

示例 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)


Python3
# Python3 program for the error in
# remove() method
 
 
# removes 'e' from list2
list2 = [ 'a', 'b', 'c', 'd' ]
 
list2.remove('e')
print(list2)


Python3
# My List
list2 = [ 'a', 'b', 'c', 'd', 'd', 'e', 'd' ]
 
# removing 'd'
list2.remove('d')
 
print(list2)


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)


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)


输出:

[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:在具有重复元素的列表上使用remove () 方法 

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]