简体   繁体   English

条件满足时停止 for 循环或 while 循环

[英]Stop for loop or while loop when condition met

I am newby in programming.我是编程新手。 The goal is to count numbers in list in order, but loop has to stop when condition is met or close to it, but must not exceed it.目标是按顺序计算列表中的数字,但循环必须在满足或接近条件时停止,但不能超过它。

For example: list = [4,4,4,3,3], condition = 11 Expected output will be 4+4=8, because another 4 will exceed condition(4+4+4=12).例如:list = [4,4,4,3,3], condition = 11 预期输出将是 4+4=8,因为另外 4 将超过条件 (4+4+4=12)。

list = [4,4,4,3,3]
condition = 11
def for_fun(list, condition):
    sum_of_sizes = 0
    for i in list:
        sum_of_sizes += i
        if sum_of_sizes <= condition:
            break

    return sum_of_sizes

I find easier to work with for loops although while loop might be better for this task.我发现使用 for 循环更容易,尽管 while 循环可能更适合此任务。

I suggest you check if your next sum_of_sizes is greater or equal than your condition and break if this is the case.我建议您检查下一个 sum_of_sizes 是否大于或等于您的条件,如果是这种情况则中断。 If not, just proceed to add items from your list.如果没有,只需继续从列表中添加项目。 Also, list is a built-in function, so please call your list something else like input_list:此外,list 是一个内置函数,因此请将您的列表称为 input_list 之类的其他名称:

input_list = [4,4,4,3,3]
condition = 11

def for_fun(input_list, condition):
    """A function that adds up numbers and breaks if the next iteration would exceed condition"""
    
    # initial sum of numbers
    sum_of_sizes = 0
    
    # iterate over your input list
    for i in input_list:

        # if the next sum of numbers would exceed condition, break
        if sum_of_sizes+i > condition:
            break

        # add up numbers
        sum_of_sizes += i

    # return the sum at the end
    return sum_of_sizes

# call and print your function, hand over your variables input_list and condition
print(for_fun(input_list=input_list, condition=condition))

To add a solution using while to @matle 's solution:使用while添加解决方案到@matle 的解决方案:

list = [4,4,4,3,3]
condition = 11
def for_fun(list, condition):
    sum_of_sizes = 0
    index = 0
    while True:
        if sum_of_sizes + list[index] > condition:
            break
        sum_of_sizes += list[index]
        index += 1
    return sum_of_sizes
        
print(for_fun(list, condition))

And please try to avoid overwriting python keywords like list !并且请尽量避免覆盖像list这样的 Python 关键字!

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

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