![](/img/trans.png)
[英]How to sum up negative and positive numbers in a list based on the row they occur
[英]How to sum up subtractions of 2 numbers in a list?
每次有变化时,您都会收到一份清单,其中列出了商店中有多少人添加到列表中。 例如 - 一开始有 0 人,然后 2 人进来,所以商店里有 2 人,当 2 人进来时有 4 人,但 3 人离开时 1 人,然后又有 2 人进来时 3 人。所以输入列表看起来像 0 2 4 1 3。你必须编写一个程序来计算商店里的总人数,在这种情况下,它将是 6。
a=[int(i)for i in input().split()]
for i in range (1,len(a)):
if a[i] > a[i-1]:
b = a[i] - a[i-1]
据我所知。 如果数字大于前一个,我就减去,现在我必须总结所有的减法。 我怎么做?
创建一个total
变量。 每次计算b
时,从a[0]
添加到它。
a = [int(i) for i in input().split()]
total = a[0]
for i in range(1, len(a)):
if a[i] > a[i-1]:
b = a[i] - a[i-1]
total += b
从逻辑上讲,您应该添加所有正的成对差异。
a = [0] + [int(i) for i in input().split()]
total = sum(max(0, y-x) for x, y in zip(a, a[1:]))
前面附加的0
代表一开始店里有人的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.