python - 为什么这些函数相同,但输出的值不同?
问题描述
我写了一个函数来计算一个列表的平均值,并且不包括零,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)
解决方案
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])
推荐阅读
- javascript - 如何过滤特定日期的数据
- python - 为 timedelta 字段的 pandas.groupby().sum() 返回 NaN
- php - Laravel 无法从包中运行测试
- android - 复选框列表视图滚动问题
- azure - 发送异步任务
在 MASTRANNSIT 中从接收者到发送者 - python - 我无法在 Jupyter Notebooks 中的 PySpark 上执行 DataFrame.take(n)。为什么?
- docker - 如何从 Windows 的 Docker 桌面公开 2375
- sql - 计数分组,并为禁用添加类别
- firebase-hosting - Firebase 托管配置
- stripe-payments - 无法从连接的帐户进行 Stripe API 调用