函数表达式不计算输出

时间:2019-04-25 04:20:11

标签: python

所以我写了一个函数来计算列表中每行/每行的平均值,但是第二个for循环之后什么也没有。有人知道为什么会这样吗?

file = [['row1', 0.0, 0.43040101296460226, 0.5630063803768022, 0.7350113237283908, 0.35384226982728356, 1.0],['row2', 0.0, 0.5884873389626358, 0.6396995276767564, 0.7329666273317014, 0.4842313879485761, 1.0],['row3', 0.0, 0.3198112142984678, 0.688061628145554, 0.9057703742992778]]
def my_mean1(file):
    # This function calculates the mean value of each column in the file
    mean_list = []
    for line in range(1,len(file[0])):
        column_values = [i[line] for i in file]
        print(column_values)
        for x in range(1,len(column_values[0])):
            if x is float and x is not None:
                print(x)
                mean_calc = sum(column_values[1:]) / len(column_values[1:])
                print(mean_calc)
                mean_list.append(mean_calc)
    print("The mean values are {0}".format(mean_list))

它适用于以下内容,但我希望它适用于方程式/表达式而不是stats模块。

mean_list = []
    for j in range(1,len(file[0])):
        column_values = [i[j] for i in file]
        mean_list.append(statistics.mean(x for x in column_values[1:] if x is not None)) 

我得到的结果

The mean values are [] # are not being calculated? 

没有错误,但是我应该得到输出

The mean values are [0.5137101644828465, 0.5742308136532783, 0.5607741464705536]

any suggestions?

1 个答案:

答案 0 :(得分:0)

if x is float不检查x是否为浮点数。

改为使用isinstance()

if isinstance(x, float):
    # Do something