[英]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.