[英]Calculate and return the average of only the positive values in the list
Ignore all the negative elements, and only use positive elements to calculate average. 忽略所有负元素,仅使用正元素来计算平均值。
ave_pos([3, -3, 4, 0, 2, -1]) = 3
Here is what I have so far and I am completely lost on why it's not working! 这是我到目前为止所拥有的,而我完全迷失了为什么它不起作用!
def ave_pos(nums):
avg = 0
for x in nums:
if x > 0:
avg = avg + x
return avg
use filter and sum for this:- 为此使用过滤器和求和:
a = [3, -3, 4, 0, 2, -1]
apositive = filter(lambda x:x>0, a)
sum(apositive)/len(apositive)
The problem is that you are just adding up all the positive elements, not computing their average. 问题是您只是将所有积极因素加在一起,而不是计算它们的平均值。 Your variable avg
ends up with the sum of all positive elements. avg
变量avg
以所有正元素的总和结束。 To get the average, you need to divide the sum by how many there were. 要获得平均值,您需要将总和除以多少。 Here's a modification of your code that works: 这是对您的代码的有效修改:
def ave_pos(nums):
total = 0
count = 0
for x in nums:
if x > 0:
total += x
count += 1
return float(total) / count
As you can see, it maintains the running total and count separately, and divides them out at the end. 如您所见,它分别维护运行总计和计数,并在最后将它们划分。 If you're using Python 2, then you need the call to float
otherwise the division will round down to the next integer. 如果您使用的是Python 2,则需要调用float
否则除法将舍入到下一个整数。 In Python 3 this isn't necessary. 在Python 3中,这不是必需的。
You can use a list comprehension to extract all the positive numbers into another list. 您可以使用列表推导将所有正数提取到另一个列表中。
def mean_positive(L):
# Get all positive numbers into another list
pos_only = [x for x in L if x > 0]
if pos_only:
return sum(pos_only) / len(pos_only)
raise ValueError('No postive numbers in input')
A little bit more and your problem can be solved by yourself: you just need to divide the sum by the number of the positive elements: 多一点,您可以自己解决问题:您只需要将总和除以积极元素的数量即可:
def ave_pos(nums):
avg = 0
pos = 0
for x in nums:
if x > 0:
pos = pos + 1
avg = avg + x
avg = avg / pos
return avg
the formula to calculate average is total_sum / number_of_elements 计算平均值的公式是total_sum / number_of_elements
Use a count variable to count no of positive element and return sum/count 使用计数变量对正元素进行计数并返回总和/计数
count =0;
sum = 0
for x in nums:
if x > 0:
sum = sum + x
count = count + 1
return avg/count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.