添加除特定数字外的数字总和/python
使用python的新手。我想知道如何使用添加除特定数字外的数字总和/python,python,Python,使用python的新手。我想知道如何使用while循环创建一个函数来获取列表中某个数字之前的数字总和。例如,我想在列表中弹出的数字3[1,2,5,2,3,2]应该是10之前,得到所有数字的总和。使用我的错误代码,我的函数不考虑3,只是添加所有的数字。 def nothree(nt): while nt != 3: list_sum = sum(nt) return list_sum 可用于此模式: from itertools import takew
while
循环创建一个函数来获取列表中某个数字之前的数字总和。例如,我想在列表中弹出的数字3[1,2,5,2,3,2]应该是10之前,得到所有数字的总和。使用我的错误代码,我的函数不考虑3,只是添加所有的数字。
def nothree(nt):
while nt != 3:
list_sum = sum(nt)
return list_sum
可用于此模式:
from itertools import takewhile
def nothree(nt):
return sum(takewhile(lambda x: x != 3, nt))
>>> nothree([1, 2, 5, 2, 3, 1])
10
虽然Fejs为您介绍了一个基于循环的指导性解决方案,但我可能会添加这一行代码,它可以在没有任何库的情况下工作:
return sum(x if x != 3 else next(iter([])) for x in nt)
其中,next(iter([])
引发的StopIteration
将在第一个3
上停止生成器,如下所示:
def nothree(nt):
sum = 0
for n in nt:
if n == 3:
break
sum += n
return sum
如果列表中有3,它将中断循环并返回在达到3之前的数字总和。如果列表中没有3,则总和将是列表的总和。最后,若列表中并没有数字,则总和为0。你们也可以只做一行
nt = [1,2,5,2,3,2]
x = sum(nt[:nt.index(3)])
nt[:nt.index(3)]
将在列表中第一次出现3
之前为您提供列表。例如,[1,2,5,2]
def nothree(nt):
i = 0
sum = 0
while nt[i]:
if nt[i] is 3:
break
sum += nt[i]
i += 1
return sum
这样,无论出于何种原因,都可以保持while循环。但在python中,您也可以执行以下操作:
def nothree(nt):
for i in nt[:-2]:
sum += [i]
return list_sum
虽然这很简洁,但它会迭代三次,一次查找索引,一次构建切片,一次求和。如果没有
3
,它根本不起作用。