我写了一个函数来计算一个列表的平均值,不包括零,mean_val(
) 是应该输出 5.2200932159502855
的函数,但它输出 6.525116519937857
即使相同的公式。
mean_val2
函数具有正确的输出:5.2200932159502855
但该函数不排除零。
如何使 mean_val()
输出 5.2200932159502855
,同时从列表中排除零,同时保持这种 for 循环格式?
这是代码+测试代码:
val = [4, 3, 5, 0, 9, 3, 6, 0, 14, 15]
val1 = [4, 3, 5, 9, 3, 6, 14, 15]
def mean_val2(val1):
sum = 0
for i in val1:
print(i)
sum += 1 / i
output = len(val1)/sum
return output
def mean_val(val):
sum = 0
for i in val:
if i != 0:
print(i)
sum += 1 / i
output2 = len(val)/sum
return output2
mean_out2 = mean_val2(val1) # 5.2200932159502855 correct output
mean_out = mean_val(val) # 6.525116519937857
print (mean_out, mean_out2)
答案 0 :(得分:5)
val 和 val1 的 len
不同。
len(val)
是 10。
len(val1)
是 8
除以 len/sum
会得到不同的结果。
您可以添加一个计数器来跟踪您处理的元素的长度:
val = [4, 3, 5, 0, 9, 3, 6, 0, 14, 15]
val1 = [4, 3, 5, 9, 3, 6, 14, 15]
def mean_val2(val1_param):
total = 0
for i in val1_param:
total += 1 / i
output = len(val1_param) / total
return output
def mean_val(val_param):
total = 0
non_zero_length = 0
for i in val_param:
if i != 0:
total += 1 / i
non_zero_length += 1
output2 = non_zero_length / total
return output2
mean_out2 = mean_val2(val1)
mean_out = mean_val(val)
print(mean_out, mean_out2)
print(mean_out == mean_out2)
输出:
5.2200932159502855 5.2200932159502855
True
一般注意事项:
sum
,因为它会遮蔽内置函数 sum 的名称。我在修改后的代码中将其更改为总计。_param
后缀,但更有意义的变量名称会更好。您还可以重用您的函数。您可以过滤掉列表中的 0 并将其传递给您的 mean_val2
函数
def mean_val(val_param):
return mean_val2([i for i in val_param if i != 0])
def mean_val2(val1_param):
total = 0
for i in val1_param:
total += 1 / i
output = len(val1_param) / total
return output
理解:
def mean_val(lst):
# Filter Out 0 Elements From List
return mean_val2([i for i in lst if i != 0])
def mean_val2(lst):
# Process List with No Zeros
return len(lst) / sum([1 / i for i in lst])
答案 1 :(得分:0)
我会为两个列表使用一个函数:
val = [4, 3, 5, 0, 9, 3, 6, 0, 14, 15]
val1 = [4, 3, 5, 9, 3, 6, 14, 15]
def mean_val(val=[]) -> float:
sum_rec = 0
zeros = 0
for i in val:
if i != 0:
print(i)
sum_rec += 1 / i
else:
zeros += 1
output2 = (len(val) - zeros) / sum_rec
return output2
mean_out2 = mean_val(val1) # 5.2200932159502855 correct output
mean_out = mean_val(val) # 5.2200932159502855 correct output
print (mean_out, mean_out2)