本文介绍了python函数在数组中查找正数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个函数,该函数接受一个数字数组并找到所有数字的最大和。换句话说,我需要找到正数之和。我写了这个,我得到列表超出范围
i need to write a function that takes an array of numbers and finds the maximum sum of all the numbers. In other words, I need to find the sum of just the positive numbers. I wrote this, I'm getting "list is out of range"
想法?
def maximum_sub(A):
x = 0
i = 0
for i in A:
while A[i] > 0:
x+=A[i]
i+=1
return x
推荐答案
使用超级功能并列出列表,而不是:
Use super functions and list comprehension instead:
>>> a = [1, 2, 3, -4, 5, -3, 7, 8, 9, 6, 4, -7]
>>> sum(x for x in a if x > 0)
45
[如果x> 0]
将创建一个由 a
中的正值组成的数组。
[x for x in a if x > 0]
will create an array made of the positive values in a
.
sum(...)
将返回该数组中元素的总和。
sum(...)
will return the sum of the elements in that array.
这篇关于python函数在数组中查找正数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!