除某个数字外的数字总和/python

2024-10-03 15:32:23 发布

您现在位置: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

Tags: 函数列表returndef数字listsumwhile
3条回答

可以将^{}用于此模式:

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。你知道吗

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

相关问题 更多 >