📜  Python|异构列表中的整数求和

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

Python|异构列表中的整数求和

有时,在使用Python时,我们可能会遇到需要查找列表总和的问题。这个问题比较容易解决。但是如果我们有混合的数据类型,这可能会变得复杂。让我们讨论可以执行此任务的某些方式。

方法 #1:使用类型转换 + 异常处理
我们可以使用蛮力方法对每个元素进行类型化,并在发生任何异常时捕获异常。这可以确保只有整数与 sum 相加,从而可以解决问题。

Python3
# Python3 code to demonstrate working of
# Summation of integers in heterogeneous list
# using type caste and exception handling
  
# initializing list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Summation of integers in heterogeneous list
# using type caste and exception handling
res = 0
for ele in test_list:
    try:
        res += int(ele)
    except :
        pass
  
# printing result 
print("Summation of integers in list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Summation of integers in heterogeneous list
# using sum() + isinstance()
  
# initializing list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Summation of integers in heterogeneous list
# using sum() + isinstance()
res = sum(filter(lambda i: isinstance(i, int), test_list))
  
# printing result 
print("Summation of integers in list : " + str(res))


输出 :
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9]
Summation of integers in list : 28

方法 #2:使用 sum() + isinstance()
这个问题也可以使用 sum() 的内置函数来解决,它还支持使用 isinstance() 的实例过滤器,它可以输入整数,从而解决问题。

Python3

# Python3 code to demonstrate working of
# Summation of integers in heterogeneous list
# using sum() + isinstance()
  
# initializing list
test_list = [5, 6, "gfg", 8, (5, 7), 'is', 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Summation of integers in heterogeneous list
# using sum() + isinstance()
res = sum(filter(lambda i: isinstance(i, int), test_list))
  
# printing result 
print("Summation of integers in list : " + str(res))
输出 :
The original list is : [5, 6, 'gfg', 8, (5, 7), 'is', 9]
Summation of integers in list : 28