📜  Python – 元素移除后的求和

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

Python – 元素移除后的求和

有时我们需要执行从其他列表中存在的列表中删除所有项目的操作,即我们在一个列表中给出了一些无效数字,需要从原始列表中删除并执行其求和。让我们讨论可以执行此操作的各种方式。

方法 #1:使用列表理解 + sum()
列表推导式可用于仅在一行中执行简单的方法,因此提供了一种简单的方法来执行此特定任务。执行求和的任务是使用 sum() 完成的。

# Python 3 code to demonstrate 
# Summation after elements removal
# using list comprehension + sum()
  
# initializing list 
test_list = [1, 3, 4, 6, 7, 6]
  
# initializing remove list 
remove_list = [3, 6]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# printing remove list 
print ("The remove list is : " + str(remove_list))
  
# using list comprehension + sum() to perform task
res = sum([i for i in test_list if i not in remove_list])
  
# printing result
print ("The list after performing removal summation is : " + str(res))
输出 :
The original list is : [1, 3, 4, 6, 7, 6]
The remove list is : [3, 6]
The list after performing removal summation is : 12

方法 #2:使用filter() + lambda + sum()
filter函数可以与 lambda 一起使用来执行此任务并创建一个新的过滤列表,其中包含删除元素列表中不存在的所有元素。执行求和的任务是使用 sum() 完成的。

# Python 3 code to demonstrate 
# Summation after elements removal
# using filter() + lambda + sum()
  
# initializing list 
test_list = [1, 3, 4, 6, 7]
  
# initializing remove list 
remove_list = [3, 6]
  
# printing original list 
print ("The original list is : " + str(test_list))
  
# printing remove list 
print ("The remove list is : " + str(remove_list))
  
# using filter() + lambda + sum() to perform task
res = sum(filter(lambda i: i not in remove_list, test_list))
  
# printing result
print ("The list after performing removal summation is : " + str(res))
输出 :
The original list is : [1, 3, 4, 6, 7, 6]
The remove list is : [3, 6]
The list after performing removal summation is : 12