Python|列表中的数字总和
求数位总和的问题很常见。这有时可以以列表的形式出现,我们需要执行它。这在许多领域都有应用,例如学校编程和网络开发。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用循环 + str()
这是执行此特定任务的蛮力方法。在此,我们为每个元素运行一个循环,将每个数字转换为字符串,并计算每个数字的总和。
Python3
# Python3 code to demonstrate
# Sum of number digits in List
# using loop + str()
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print("The original list is : " + str(test_list))
# Sum of number digits in List
# using loop + str()
res = []
for ele in test_list:
sum = 0
for digit in str(ele):
sum += int(digit)
res.append(sum)
# printing result
print ("List Integer Summation : " + str(res))
Python3
# Python3 code to demonstrate
# Sum of number digits in List
# using sum() + list comprehension
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print("The original list is : " + str(test_list))
# Sum of number digits in List
# using sum() + list comprehension
res = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list))
# printing result
print ("List Integer Summation : " + str(res))
Python3
# Python3 code to demonstrate
# Sum of number digits in a List
# using sum() + reduce()
from functools import reduce
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print("The original list is : " + str(test_list))
# Sum of number digits in List
# using sum() + reduce()
res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list]
# printing result
print("List Integer Summation : " + str(res))
输出 :
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
方法 #2:使用 sum() + 列表推导
也可以使用上述功能使用速记来执行此任务。 sum() 用于计算求和,列表推导用于计算迭代。
Python3
# Python3 code to demonstrate
# Sum of number digits in List
# using sum() + list comprehension
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print("The original list is : " + str(test_list))
# Sum of number digits in List
# using sum() + list comprehension
res = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list))
# printing result
print ("List Integer Summation : " + str(res))
输出 :
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
方法#3:使用 sum() + reduce()
也可以使用上述功能使用速记来执行此任务。 sum() 用于计算来自 functools 模块的求和和归约函数。
Python3
# Python3 code to demonstrate
# Sum of number digits in a List
# using sum() + reduce()
from functools import reduce
# Initializing list
test_list = [12, 67, 98, 34]
# printing original list
print("The original list is : " + str(test_list))
# Sum of number digits in List
# using sum() + reduce()
res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list]
# printing result
print("List Integer Summation : " + str(res))
输出:
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]