【问题标题】:How do I use the sum() function in Python to find the sum of all positive numbers in a list?如何使用 Python 中的 sum() 函数来查找列表中所有正数的总和?
【发布时间】:2021-03-09 17:41:27
【问题描述】:

编辑 1: 已解决!解决方案是使用@sushanth 给我的i for i in arr if i > 0

代码的最终产品:

def positive_sum(arr):
    return sum(i for i in arr if i > 0)

我正在尝试完成一些 Codewars 挑战,但遇到了一个问题。我得到了一个正数和负数的列表,我应该找到所有正数的总和。

这是我已经拥有的:

def positive_sum(arr):
    for n in arr:
        if n < 0:
            arr.remove(n)
    return sum(arr)

以下是我应该处理的列表:

[1,2,3,4,5]
[1,-2,3,4,5]
[-1,2,3,4,-5]
[]      
[-1,-2,-3,-4,-5]

但是,每当我运行测试时,除了最后一个测试之外,所有测试都通过了,所有测试都是负数。出于某种原因,它的结果是-6,即使所有负数都应该被删除。

这是为什么?我应该怎么做才能确保所有测试都通过?

【问题讨论】:

  • 可以用sum(i for i in arr if i &gt; 0)代替remove ?
  • 在迭代列表时不要从列表中删除。你弄乱了迭代器,这可能导致元素被跳过。
  • @sushanth 是的,成功了!我从另一个 stackoverflow 帖子中做了类似的事情,但我认为它是为了在另一个用例中使用。这个效果很好!
  • @Carcigenicate 哦,好吧。感谢您的提示!
  • 这能回答你的问题吗? How to remove items from a list while iterating?

标签: python list testing calculation


【解决方案1】:

使用生成器和 if 条件尝试 sum()

result = sum(x for x in [1, 2, 3, 4, 5] if x > 0)
print(result)

【讨论】:

  • 不需要使用list 理解,sum() 可以将生成器作为参数。首先创建list 会浪费内存和计算时间。
  • 虽然,玩弄它。生成器表达式也往往较慢,因此对于小型列表,如果可以接受额外的内存使用,则推导式可能是更好的选择。
  • 完全同意,改成generator,不错,谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-06-16
  • 2020-04-06
  • 2012-04-02
  • 2015-10-31
  • 2014-09-22
  • 2013-12-06
  • 2013-09-14
  • 2022-11-25
相关资源
最近更新 更多