📜  Python|在字符串和数字的混合列表中乘以整数

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

Python|在字符串和数字的混合列表中乘以整数

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

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

# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
# using type caste and exception handling
  
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Mixed List Integer Multiplication
# using type caste and exception handling
res = 1
for ele in test_list:
    try:
        res *= int(ele)
    except :
        pass
  
# printing result 
print("Product of integers in list : " + str(res))
输出 :
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

方法 #2:使用循环 + isinstance()
这是可以执行此任务的蛮力方式。在此,我们在所有元素上运行一个循环,并且仅当我们使用 isinstance() 找到整数时才执行乘法。

# Python3 code to demonstrate working of
# Mixed List Integer Multiplication
# using loop + isinstance()
  
# initializing list
test_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Mixed List Integer Multiplication
# using loop + isinstance()
res = 1
for ele in test_list:
    if(isinstance(ele, int)):
        res *= ele
  
# printing result 
print("Product of integers in list : " + str(res))
输出 :
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640