如何调试此错误? 'generator'类型的对象没有len()

时间:2019-04-21 14:59:05

标签: python

我正在尝试计算列表列表中数字的平均值,我应该跳过第一个观察值(即位置0),因为它们是国家/地区的名称,我只需要计算[0]之后的每一列的平均值。但是,我的代码一直在说:

TypeError: object of type 'generator' has no len()

如果有人可以看一下并提供帮助,我将不胜感激。谢谢!

我尝试了以下代码:

def my_mean1(file):    
    mean_list = []
    for column in range(1,len(file[0])):
        column_values = (row[column] for row in file)

        # calculate the mean but not with the statistics module
        mean_values = sum(column_values) / len(column_values)
        mean_list.append(mean_values(x for x in column_values if x is not None))    
    return mean_list

我期望的结果

test = [['str1', 2.66171813, 7.460143566, 0.490880072, 52.33952713, 0.427010864, -0.106340349, 0.261178523], ['str2', 4.639548302, 9.373718262, 0.637698293, 69.05165863, 0.74961102, -0.035140377, 0.457737535]]
test1 = data(file) # a function that made the list of lists
my_mean(test)
[5.022380471333333, 9.327360550833333, 0.7483190200000001, 65.42301750166666, 0.6615842928333333, -0.05882061216666667, 0.3449308604]

但是使用test

时遇到的错误
TypeError: object of type 'generator' has no len()

以及尝试test1

时遇到的错误
TypeError: unsupported operand type(s) for +: 'int' and 'str'

1 个答案:

答案 0 :(得分:0)

column_values = (row[column] for row in file)

用方括号替换括号,以便获得返回的列表,而不是生成器类型。 []