如何从Python中的列表中删除多个元素?完整实现

2021年3月30日10:12:44 发表评论 596 次浏览

给定一个数字列表, 编写一个Python程序, 根据给定条件从列表中删除多个元素

例子:

Input: [12, 15, 3, 10]
Output: Remove = [12, 3], New_List = [15, 10]

Input: [11, 5, 17, 18, 23, 50]
Output: Remove = [1:5], New_list = [11, 50]

根据我们对数据的了解, 可以从Python列表中删除多个元素。就像, 我们只知道要删除的值或这些值的索引。让我们看一下基于不同场景的不同示例。

示例1:假设我们要删除列表中可以被2或所有偶数整除的每个元素。

# Python program to remove multiple
# elements from a list 
  
# creating a list
list1 = [ 11 , 5 , 17 , 18 , 23 , 50 ] 
  
# Iterate each element in list
# and add them in variale total
for ele in list1:
     if ele % 2 = = 0 :
         list1.remove(ele)
  
# printing modified list
print ( "New list after removing all even numbers: " , list1)

输出如下:

New list after removing all even numbers:  [11, 5, 17, 23]

示例2:

使用列表理解

删除列表中的所有偶数元素与仅包括非偶数元素(即奇数元素)一样好。

# Python program to remove multiple
# elements from a list 
  
# creating a list
list1 = [ 11 , 5 , 17 , 18 , 23 , 50 ] 
  
# will create a new list, # excluding all even numbers
list1 = [ elem for elem in list1 if elem % 2 ! = 0 ]
  
print ( * list1)

输出如下:

11 5 17 23

示例3:

使用列表切片移除相邻元素

在Python代码下面, 从索引1到4删除值。

# Python program to remove multiple
# elements from a list 
  
# creating a list
list1 = [ 11 , 5 , 17 , 18 , 23 , 50 ] 
  
# removes elements from index 1 to 4
# i.e. 5, 17, 18, 23 will be deleted
del list1[ 1 : 5 ]
  
print ( * list1)

输出如下:

11 50

示例4:

使用列表理解

假设要删除的元素是已知的, 而不是这些元素的索引。在这种情况下, 我们可以直接消除那些元素, 而不必关心在下一个示例中将看到的索引。

# Python program to remove multiple
# elements from a list 
  
# creating a list
list1 = [ 11 , 5 , 17 , 18 , 23 , 50 ] 
  
# items to be removed
unwanted_num = { 11 , 5 }
  
list1 = [ele for ele in list1 if ele not in unwanted_num]
  
# printing modified list
print ( "New list after removing unwanted numbers: " , list1)

输出如下:

New list after removing unwanted numbers:  [17, 18, 23, 50]

示例5:元素索引何时已知。

尽管已知元素的索引, 但是随机删除元素会更改索引的值。因此, 始终建议先删除最大的索引。使用此策略, 较小值的索引将不会更改。我们可以以相反的顺序对列表进行排序, 并以降序删除列表中的元素。

# Python program to remove multiple
# elements from a list 
  
# creating a list
list1 = [ 11 , 5 , 17 , 18 , 23 , 50 ] 
  
# given index of elements 
# removes 11, 18, 23
unwanted = [ 0 , 3 , 4 ]
  
for ele in sorted (unwanted, reverse = True ): 
     del list1[ele]
  
# printing modified list
print ( * list1)

输出如下:

5 17 50

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: