我试图对列表中每个元素的数字求和并立即打印每个元素的总和,但下面的代码只给出 6 6 6。我想要的输出是 6 1 2。
#pythonCode#
my_list = [15, 10, 20]
sum = 0
m = ""
for i in range(0, 3):
while m != 0:
rem= my_list[i] % 10
m = my_list[i] //10
my_list[i] = m
sum = sum + rem
print(sum)
最佳答案
您可以使用map
来做到这一点应用 lambda 函数 - 如果我正确理解所需的输出:
>>> my_list = [15, 10, 20]
>>> list(map(lambda x: sum(int(s) for s in str(x)), my_list))
[6, 1, 2]
完整地写出来,这大致相当于:
my_list = [15, 10, 20]
for integer in my_list:
total = 0
for digit in str(integer):
total += int(digit)
print(f"The sum of {integer} is {total}")
输出:
The sum of 15 is 6
The sum of 10 is 1
The sum of 20 is 2
关于python - 列表中每个整数的数字总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59632232/