Python – 获取字符串列表中数字的总和
有时,在处理数据时,我们可能会遇到一个问题,即我们会收到一系列带有字符串格式数据的列表,我们希望将这些列表累积为列表。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + int()
这是执行此任务的蛮力方法。在此,我们为整个列表运行一个循环,将每个字符串转换为整数并按列表执行求和并存储在一个单独的列表中。
# Python3 code to demonstrate working of
# Summation of String Integer lists
# using loop + int()
# initialize list
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
# printing original list
print("The original list : " + str(test_list))
# Summation of String Integer lists
# using loop + int()
res = []
for sub in test_list:
par_sum = 0
for ele in sub:
par_sum = par_sum + int(ele)
res.append(par_sum)
# printing result
print("List after summation of nested string lists : " + str(res))
输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after summation of nested string lists : [5, 11, 17]
方法 #2:使用sum() + int()
+ 列表推导
这是可以执行此任务的简写。在此,我们使用列表推导在列表上运行一个循环,并使用 sum() 提取总和。
# Python3 code to demonstrate working of
# Summation of String Integer lists
# using sum() + int() + list comprehension
# initialize list
test_list = [['1', '4'], ['5', '6'], ['7', '10']]
# printing original list
print("The original list : " + str(test_list))
# Summation of String Integer lists
# using sum() + int() + list comprehension
res = [sum(int(ele) for ele in sub) for sub in test_list]
# printing result
print("List after summation of nested string lists : " + str(res))
输出 :
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after summation of nested string lists : [5, 11, 17]