python - 列表中每个整数的数字总和

标签 python python-3.x list sum integer

我试图对列表中每个元素的数字求和并立即打印每个元素的总和,但下面的代码只给出 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/

相关文章:

python - 如何将从 elasticsearch 返回的 64 位时间戳转换为 python 中的日期时间?

python - 一种快速查找列表交集元素数量的方法(Python)

python - Argparse 需要带有可变参数的选项吗?

python - 如何将项目附加到 python 列表中的列表?

c# - 对列表中的月份和年份进行排序

python - Pandas:更快地将字符串元组列表转换为数据帧?

python - 从 pandas df 中选择特定列

python - os.walk 排除 .svn 文件夹

python - python d 中的错误未定义。

python-3.x - ValueError : Cannot feed value of shape (100, 1) 对于张量 'Placeholder_1:0' ,其形状为 '(?, 10)'