计算列表的总和并删除 -1 值

我想编写一个 python 程序,如果最后一个元素是 -1 打印 -1,则给定一个用户输入列表,然后如果列表中的任何元素包含不应该计数的 -1 和剩余的数组总和。


例如:


1) list=[1,2,3,4,5] ans should be 15 


2) list=[1,2,3,4,-1] ans should be -1

3) list=[1,2,-1,4,5] ans should be 12 ignoring "-1"

我尝试了 2 种解决方案,但都没有用。


import sys

def totalcost(ar):


  if ar[-1]==-1:

    return -1

  else:

    summ=0

    for elem in ar:

        if(ar[elem]==-1):

            ar.remove(elem)

            summ=summ+elem

        else:        

            summ=summ+elem      

        return summ

if __name__=='__main__':

  ar_city=input()

  ar=list(map(int,input().strip().split()))

  result=totalcost(ar)

  print(result)  

import sys

def totalcost(ar):


  if ar[-1]==-1:

    return -1

  else:

    summ=0

    for elem in ar:

        if(ar[elem]<0):

            ar_new=ar.remove(elem)

            for i in ar_new:

                summ=summ+i

        else:        

            summ=summ+elem      

        return summ

if __name__=='__main__':

  ar_city=input()

  ar=list(map(int,input().strip().split()))

  result=totalcost(ar)

  print(result)  


largeQ
浏览 108回答 4
4回答

尚方宝剑之说

这是一个可能的解决方案:def totalcost(ar):&nbsp; &nbsp; return -1 if ar[-1] == -1 else sum(x for x in ar if x != -1)如果您不想要使用列表理解的单行解决方案,您可以执行以下操作:def totalcost(ar):&nbsp; &nbsp; if ar[-1] == -1:&nbsp; &nbsp; &nbsp; &nbsp; return -1&nbsp; &nbsp; s = 0&nbsp; &nbsp; for x in ar:&nbsp; &nbsp; &nbsp; &nbsp; if x != -1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s += x&nbsp; &nbsp; return s

千万里不及你

您可以使用一些简单的功能来改善您的生活:sum(filter(lambda x: x != -1, ls))sum- 在不使用 for 循环的情况下对 iterable 求和filter- 从 iterable 中过滤掉不需要的元素。在这种情况下,我使用ls简单的lambda x: x != -1.当然,这应该在您的初始条件之后使用,如下所示:if ls[-1] == -1:     return -1     return sum(filter(lambda x: x != -1, ls))

白衣非少年

我认为您可以简单地使用 filter 和 sum 以及 lambda 来实现。只是稍微更新了你的 totalcost 函数import sysdef totalcost(ar):    if ar[-1] == -1:        return -1    else:        ar_filtered = filter(lambda x: x > 0, ar)        return sum(ar_filtered)if __name__ == '__main__':    ar_city = [1, 2, 3, 4, 5]    assert totalcost(ar_city) == 15    ar_city = [1, 2, 3, 4, -1]    assert totalcost(ar_city) == -1    ar_city = [1, 2, -1, 4, 5]    assert totalcost(ar_city) == 12

ITMISS

以下是你犯过的错误:ar[elem]没有ar正确迭代每个元素。您在 for-in 循环中返回summ,因此它只会返回第一个元素的值。这是一个根据您的代码修改的工作示例。def totalcost(ar):&nbsp; &nbsp; if ar[-1] == -1:&nbsp; &nbsp; &nbsp; &nbsp; return -1&nbsp; &nbsp; summ = 0&nbsp; &nbsp; for elem in ar:&nbsp; &nbsp; &nbsp; &nbsp; if(elem != -1):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; summ += elem&nbsp; &nbsp; return summ
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python