Python-任何列表中非负整数的平均值



Python新手,第二周。这里的目标是编写一个程序,它可以找到任何列表的非负值的平均值,而不仅仅是提供的列表。

numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
average = 0
# write your code here so that it sets average
# to the average of the non-negative numbers
num = list(numbers)
avg = sum(num (num >= 0)) / len(num)
average == avg
print(average)
return average

输出:第10行出现错误:对于范围(num(中的n^SyntaxError:语法无效

我可以编译的另一个版本:

numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
average = 0
num = int.input(numbers (numbers >= 0))
for n in range(num)
positive_integers = float(input(numbers))
total += positive_integers
average = total / length(num)
print(average)
return average

输出:第9行出现错误:对于范围(数字(中的n^SyntaxError:语法无效

你能帮我理解吗?谢谢

入门级友好解决方案:

numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
total_sum = 0
number_of_elements = 0
for number in numbers:
if number >= 0:
total_sum += number # sum of all the non negative elements
number_of_elements += 1 # count of non-negative elements in the list
average = total_sum / number_of_elements
print(average)

您提到的错误告诉您正在将列表num与不正确的int0进行比较

这是Python 中的无效语句

sum(num(num>=0((

这是你可以做的。此外,如果你想对平均值进行四舍五入,你可以简单地使用round(average,<num>) #==== Whatever number you want in <num>

numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
non_negative=[num for num in numbers if num>=0] #==== List comprehension which iterates over the numbers list and contains only those elements if condition num>=0 is met
average=sum(non_negative)/len(non_negative) #=== Sum is the sum of all elements in the list, len is the number of elements of the lists
print("Average is: ",average)

除非有特定的性能原因,比如处理数亿个数字,并且RAM即将耗尽,否则我喜欢优化可读性。数学家会如何描述这个解?他们会说:

  • 查找所有非负数
  • 将该列表的总和除以列表的长度

好吧,那我们就这么做吧!

numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
average = 0
# Built a list of all of the non-negative numbers
non_negatives = [num for num in numbers if num >= 0]
# This should look familar
average = sum(non_negatives) / len(non_negatives)
print(average)

首先,这将以尽可能快的速度运行,因为C Python解释器正在完成所有繁重的工作,而不是您自己的代码。其次,当你六个月后回来,试着记住你打算做什么时,这句话的每一行都是有意义的。

一般来说,首先要使Python代码尽可能具有可读性。不要试图让它变得"聪明"或"快速",直到你知道你需要它。

相关内容