我试图编写一个Python代码,读取列表中的每个项目,并在特定条件下添加和查找该列表的平均值
所以我试着把列表中的所有数字相加,然后除以列表中不等于0的数字。代码不包括我将所有数字相加的部分。我在代码的这一部分中所做的是,我试图逐个检查列表中的每个项目。最后,它会告诉我,有多少个数字在变量sum_div中不等于零我试图编写一个Python代码,读取列表中的每个项目,并在特定条件下添加和查找该列表的平均值,python,list,Python,List,所以我试着把列表中的所有数字相加,然后除以列表中不等于0的数字。代码不包括我将所有数字相加的部分。我在代码的这一部分中所做的是,我试图逐个检查列表中的每个项目。最后,它会告诉我,有多少个数字在变量sum_div中不等于零 b=4 c=0 d=6 e=0 I_list = [ b, c, d, e] sum_div = 0 ip = I_list[0] for i in range(0, len(I_list), 1) : while ip != 0: sum_di
b=4
c=0
d=6
e=0
I_list = [ b, c, d, e]
sum_div = 0
ip = I_list[0]
for i in range(0, len(I_list), 1) :
while ip != 0:
sum_div += 1
elif ip == 0:
sum_div += 0
print(sum_div)
在这种情况下,sum_div应该等于2。您可以使用列表理解来筛选出
0
的元素,然后确定该列表的长度。然后将总和除以该长度,计算(非零元素的)平均值
从技术上讲,您还可以防止出现空列表或全零列表
try:
average = sum(I_list) / len([i for i in I_list if i])
except ZeroDivisionError:
average = whatever_here # don't know what you'd want in this case
科里上面的答案是一个巧妙的解决方案,但你的答案也差不多。你只需要做一点小小的改变:
b=4
c=0
d=6
e=0
I_list=[b,c,d,e]
sum_div=0
对于范围内的i(0,len(i_列表),1):
ip=I_列表[I]#确保更新您的值
如果ip!=0:#使用if而不是while
sum_div+=1
elif ip==0
sum_div+=0
打印(总和分区)
另一种性能更好的方法是使用numpy库
# import numpy
import numpy as np
# create a numpy array (just feed it the same list you created)
I_array = np.array([b, c, d, e])
# calculate the array sum using np.sum()
array_sum = np.sum(I_array)
# I_array > 0 returns array of True or False for each item depending on how it matches the condition of not-equal zero.
# np.sum() evaluates all True as 1 and all False as 0.
amount_of_non_zeros = np.sum(I_array != 0)
# sum of array divided by amount of non-zeros
array_sum / amount_of_non_zeros
这个代码不起作用。如果没有
if
,就不能有elif
。试着提供一个sum\u div+=0
似乎对任何事情都没有多大影响。你可能想打印出你的代码,然后用铅笔一行一行地遵循逻辑,确保你完全按照计算机的方式执行每一行,同时记下变量值。否则,请询问你的老师。请避免只回答代码,并张贴一个简短的解释为什么你的代码有效。
# import numpy
import numpy as np
# create a numpy array (just feed it the same list you created)
I_array = np.array([b, c, d, e])
# calculate the array sum using np.sum()
array_sum = np.sum(I_array)
# I_array > 0 returns array of True or False for each item depending on how it matches the condition of not-equal zero.
# np.sum() evaluates all True as 1 and all False as 0.
amount_of_non_zeros = np.sum(I_array != 0)
# sum of array divided by amount of non-zeros
array_sum / amount_of_non_zeros
I_list =[4, 0, 6, 0]
sum_div = 0
for i in I_list:
if i != 0:
sum_div += 1
print(sum_div)