[英]How to stop iterating over a list once a certain value is reached
For this problem, a list of integers is given. 对于此问题,给出了一个整数列表。 I need to find the average of the list.
我需要找到列表的平均值。 The only problem is, once you reach a negative number, you aren't supposed to factor in any of the numbers after that into the calculations.
唯一的问题是,一旦达到负数,就不应在计算之后考虑任何数字。 This is what I have so far:
这是我到目前为止的内容:
def average_rainfall(listInts):
newList = []
count = 0
for num in listInts:
if num < 0:
newList.append(listInts[:num])
count += (1*len(newList))
else:
newList.append(listInts)
count += (1*len(newList))
summ = sum(newList)
avg = summ/count
return avg
The list and function call are below: 列表和函数调用如下:
a_list = [1, 2, 3, 4, 5, -1, 6, 7]
print(average_rainfall(a_list))
I've been working on this for a while and am stuck. 我已经为此工作了一段时间,被卡住了。 Any tips?
有小费吗?
Use break
inside inside the if
block to exit the loop early. 在
if
块内部使用break
可以尽早退出循环。
Something like 就像是
def average_rainfall(listInts):
newList = []
count = 0
for num in listInts:
if num < 0:
newList.append(num)
count += 1
break
else:
newList.append(num)
count += 1
summ = sum(newList)
avg = summ/count
return avg
Edit: There is a bug in your append
statements. 编辑:您的
append
语句中有一个错误。 You need to append the num
you are currently iterating on, not the whole list. 您需要附加当前要迭代的
num
,而不是整个列表。
This is a classic use case for continue
or break
. 这是
continue
或break
的经典用例。 To determine which one that you want you have to decide whether or not you want to skip over negative numbers or stop execution entirely. 要确定您要选择哪一个,必须决定是否要跳过负数或完全停止执行。
continue
skips one iteration of the loop while break
stops execution of the loop entirely. continue
跳过循环的一个迭代,而break
停止循环的执行完全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.