Calculate variant of the numbers / TypeError: 'int' object is not callable

Calculate variant of the numbers / TypeError: 'int' object is not callable

我收到 TypeError: 'int' object is not callable on the line 27 (var = ...)

文件data1_.txt只有5行,每行一个整数。

有人可以帮我理解为什么吗?

line_number = 0;
countline = 0;
linesum = 0;
avg = 0;
var = 0;
linelist = [];

f = open("data1_.txt", "r")

while True:
#how to count lines    
    line = f.readline()
    if line == "" :
        break
    line = line.rstrip("\n\r")
    line_number += 1
    if line != "/n":
        countline += 1
#how to list the numbers     
    x = line.strip()
    linelist.append(x)
#how to sum the numbers of the list
    linesum += int(x)*1.0
    avg = linesum/countline;

#how to calculate variant of numbers
    var = sum((y-avg) **2 for y in linelist) / countline
    
f.close()

print("number of lines:", countline)
print("the numbers:", linelist)
print("sum of numbers:", linesum)
print("avarage:", avg)
print("variant:", var)

我发现了你的问题。在你的 sum 语句中,你试图比较 y 的字符串值(这是 readlines 给出的)当它应该是一个浮点值时。

试试这个:

#how to calculate variant of numbers
    var = sum((float(y)-avg) **2 for y in linelist) / countline