为什么这些函数相同,但输出的值不同?
我写了一个函数来计算列表的平均值,不包括零,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)
回答
该lenVAL和VAL1是不同的。
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
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