繁体   English   中英

对数字列表求和,直到找到数字X

[英]Sum a list of numbers until a number X is found

在我的程序中,我需要放置一个while函数,对这个列表求和,直到找到一个特定的数字:

[5,8,1,999,7,5]

输出应该为14,因为它的总和为5 + 8 + 1,并在找到999时停止。

我的主意如下:

def mentre(llista):
  while llista != 999:
    solution = sum(llista)
return solution

使用iter -function:

>>> l = [5,8,1,999,7,5]
>>> sum(iter(iter(l).next, 999))
14

iter调用第一个参数,直到找到第二个参数。 这样所有数字加起来,直到找到999。

由于您提到了使用while循环,因此可以使用itertools.takewhile尝试基于生成器的方法:

>>> from itertools import takewhile
>>> l = [5,8,1,999,7,5]
>>> sum(takewhile(lambda a: a != 999, l))
14

只要谓词( a != 999 )为真,生成器就从列表l消耗,并将这些值相加。 谓词可以是您在此处喜欢的任何内容(如普通的while循环),例如,您可以在值小于500时对列表求和。

显式使用while循环的示例如下:

def sum_until_found(lst, num):
    index = 0
    res = 0
    if num in lst:
        while index < lst.index(num):
            res += lst[index]
            index += 1
    else:
        return "The number is not in the list!"
    return res

另一种可能的方式是:

def sum_until_found(lst, num):
    index = 0
    res = 0
    found = False
    if num in lst:
        while not found:
            res += lst[index]
            index += 1
            if lst[index] == num:
                found = True
    else:
        return "The number is not in the list!"
    return res

有许多不使用while循环的方法,其中一种是使用递归:

def sum_until_found_3(lst, num, res=0):
    if num in lst:
        if lst[0] == num:
            return res
        else:
            return sum_until_found_3(lst[1:], num, res + lst[0])
    else:
        return "The number is not in the list!"

最后,一个更简单的解决方案:

def sum_until_found(lst, num):
    if num in lst:
        return sum(lst[:lst.index(num)])
    else:
        return "The number is not in the list!"

使用index和切片

def mentre(llista):
    solution = sum(lista[:lista.index(999)])
    return solution

演示版

>>> lista =  [5,8,1,999,7,5] 
>>> sum(lista[:lista.index(999)])
14

暂无
暂无

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

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