首页 > 解决方案 > 为什么这些函数相同,但输出的值不同?

问题描述

我写了一个函数来计算一个列表的平均值,并且不包括零,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)

标签: pythonpython-3.x

解决方案


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

一般注意事项:

  1. 您不应该使用变量名称sum,因为它会隐藏内置函数sum的名称。我在修改后的代码中将其更改为总计。
  2. 您的函数参数不应与在全局范围内定义的列表具有相同的名称。我添加了一个_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])

推荐阅读