简体   繁体   English

一旦达到某个值,如何停止对列表进行迭代

[英]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? 有小费吗?

You could use itertools.takewhile ( doc ): 您可以使用itertools.takewhiledoc ):

from itertools import takewhile

a_list = [1, 2, 3, 4, 5, -1, 6, 7]

def average_rainfall(listInts):
    l = [*takewhile(lambda k: k >=0, listInts)]
    return sum(l) / len(l)

print(average_rainfall(a_list))

Prints: 打印:

3.0

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 . 这是continuebreak的经典用例。 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.

相关问题 当达到某个索引值时,如何停止将数字添加到列表中的 while 循环? - How do I stop a while loop that adds numbers to a list when a certain index value is reached? 试图使循环一旦达到某个值就停止,但是它总是进行太多步骤 - Trying to get a loop to stop once a certain value is reached, but it always carries on 1 step too many 如何停止嵌套循环遍历 Python 中的列表 - How to stop a nested loop iterating over a list in Python 如何在迭代列表时跳过某些为空的索引? - How to skip certain indexes which are empty while iterating over the list? 一旦发送了一定数量的 SMS 消息,如何停止迭代? - How can I stop iterating once a certain number of SMS messages have been sent? 遍历字典中的列表值 - Iterating over a list value in a dictionary 以值作为列表遍历字典 - Iterating over a dictionary with value as a list 如何在达到EOF时停止使用itertools.islice进行迭代 - How to stop iterating using itertools.islice when EOF is reached 一旦达到/设置了某个值,如何重置 PYQT5 进度条? - How to reset a PYQT5 progress bar once a certain value has been reached/set? 遍历列表元素的列表,如果整数具有特定值,则返回错误消息 - Iterating over list of list elements and returning error message if integer has certain value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM