我正在python中使用for循环来显示旧值和新值的总和。以下是我的代码。
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print(sum)
,此循环的输出显示48
但是我想显示类似
的输出6
6+5 = 11
11+3 = 14
14+8 = 22
22+4 = 26
26+2 = 28
28+5 = 33
33+4 = 37
37+11 = 48
请让我知道我需要更改代码以显示这样的输出。
答案 0 :(得分:9)
您可以遍历列表中的元素,在循环中打印所需的内容并更新total
:
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
total = numbers[0]
print(f'{total}')
for val in numbers[1:]:
print(f'{total} + {val} = {total + val}')
total += val
# 6
# 6 + 5 = 11
# 11 + 3 = 14
# 14 + 8 = 22
# 22 + 4 = 26
# 26 + 2 = 28
# 28 + 5 = 33
# 33 + 4 = 37
# 37 + 11 = 48