📜  Python|从列表中删除给定元素

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

Python|从列表中删除给定元素

给定一个列表,编写一个Python程序从给定列表中删除给定元素(列表可能有重复项)。我们可以通过多种方式在Python中完成这项任务。让我们看看一些 Pythonic 方法来完成这项任务。

方法 #1:使用pop()方法 [删除首先找到的给定元素。]

# Python program to remove given element from the list
list1 = [1, 9, 8, 4, 9, 2, 9] 
    
# Printing initial list 
print ("original list : "+ str(list1)) 
    
remove = 9
    
# using pop() 
# to remove list element 9
if remove in list1: 
    list1.pop(list1.index(remove)) 
    
# Printing list after removal 
print ("List after element removal is : "  + str(list1)) 
输出:
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 9, 2, 9]


方法 #2:使用remove()方法

# Python program to remove given element from the list
list1 = [1, 9, 8, 4, 9, 2, 9] 
    
# Printing initial list 
print ("original list : "+ str(list1)) 
  
# using remove() to remove list element 9
list1.remove(9) 
  
  
# Printing list after removal 
print ("List after element removal is : "  + str(list1)) 
输出:
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 9, 2, 9]

现在,让我们看看删除所有给定元素的出现的方法。

方法#3:使用集合

由于列表转换为集合,所有重复项都被删除,但无法保留列表的顺序。

# Python program to remove given element from the list
list1 = [1, 9, 8, 4, 9, 2, 9] 
    
# Printing initial list 
print ("original list : "+ str(list1)) 
  
# using discard() method to remove list element 9
list1 = set(list1) 
list1.discard(9) 
    
list1 = list(list1) 
  
  
# Printing list after removal 
print ("List after element removal is : "  + str(list1)) 
输出:
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [8, 1, 2, 4]


方法#4:使用列表推导

# Python program to remove given element from the list
list1 = [1, 9, 8, 4, 9, 2, 9] 
    
# Printing initial list 
print ("original list : "+ str(list1)) 
  
# using List Comprehension 
# to remove list element 9
list1 = [ele for ele in list1 if ele != 9] 
    
# Printing list after removal 
print ("List after element removal is : "  + str(list1)) 
输出:
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 2]