📜  Python – 字符串整数乘积

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

Python – 字符串整数乘积

有时,在处理数据时,我们可能会遇到一个问题,即我们收到一系列包含字符串格式数据的列表,我们希望找到每个字符串列表整数的乘积。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + int()
这是执行此任务的蛮力方法。在此,我们为整个列表运行一个循环,将每个字符串转换为整数并按列表执行产品并存储在单独的列表中。

# Python3 code to demonstrate working of
# String Integer Product
# using loop + int()
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= int(ele)
    return res 
  
# initialize list 
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
  
# printing original list 
print("The original list : " + str(test_list))
  
# String Integer Product
# using loop + int()
res = []
for sub in test_list:
    par_prod = prod(sub)
    res.append(par_prod)
  
# printing result
print("List after product of nested string lists : " + str(res))
输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after product of nested string lists : [4, 30, 70]

方法 #2:使用循环 + int() + 列表推导
这是可以执行此任务的简写。在此,我们使用列表推导在列表上运行一个循环,并使用显式产品函数提取产品。

# Python3 code to demonstrate working of
# String Integer Product
# using loop + int() + list comprehension
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= int(ele)
    return res 
  
# initialize list 
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
  
# printing original list 
print("The original list : " + str(test_list))
  
# String Integer Product
# using loop + int() + list comprehension
res = [prod(sub) for sub in test_list]
  
# printing result
print("List after product of nested string lists : " + str(res))
输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after product of nested string lists : [4, 30, 70]