繁体   English   中英

使用 while 循环查找列表的总和,直到出现负数或列表结尾

[英]Use a while loop to find sum of list until negative number or end of list appears

我应该使用 while 循环来查找列表的总和,直到它达到负数或直到它到达列表的末尾。 以下是示例列表:

v = [ 10, 12, 3, -5, 5, 6 ]
v = [ 0, 10, 3, 6, 5, 1 ]

两个列表的 output 总和应为 25。这是我的代码:

result = 0
i = 0
for num in v:
    while num >= 0:
        result += num
        i += 1
print(result)

对于这两个列表,我的 output 只是一个空白的无限循环。 我提供的代码是我认为最有意义的代码。

使用if 、 not whilebreak提前终止循环。 此外,您不需要i

v = [ 10, 12, 3, -5, 5, 6 ]
# v = [ 0, 10, 3, 6, 5, 1 ]

sum_non_negatives = 0

for num in v:
    if num < 0:
        break
    sum_non_negatives += num
        
print(sum_non_negatives)

您应该在单个 while 循环中使用 OR 条件,如下所示:

v = [10, 12, 3, -5, 5, 6]
v = [0, 10, 3, 6, 5, 1]

result = 0
i = 0

# while the sum is still at or above 0 and the list isn't out of bounds
while v[i] >= 0 and i < len(v): 
    num = v[i]
    result += num
    i += 1

print(result)

这使您可以避免break语句,这通常是不好的编码习惯。

仅使用while (不适for ):

result = 0
i = 0
while i<len(v) and v[i] >= 0:
    result += v[i]
    i += 1
print(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM