Python 编写一个程序,读取包含两列数字的文本文件,然后计算每列的总数和平均值?
我必须编写一个程序,读取包含两列数字的文本文件,然后计算每列的总数和平均数。我能够分隔列,但当我尝试查找和时,我不断收到各种错误,如“TypeError:不支持的+操作数类型:'int'和'str'”。以下是我到目前为止的情况:Python 编写一个程序,读取包含两列数字的文本文件,然后计算每列的总数和平均值?,python,Python,我必须编写一个程序,读取包含两列数字的文本文件,然后计算每列的总数和平均数。我能够分隔列,但当我尝试查找和时,我不断收到各种错误,如“TypeError:不支持的+操作数类型:'int'和'str'”。以下是我到目前为止的情况: def main(): print("This program will read the file and calculate the total and average of each column of numbers") filename= i
def main():
print("This program will read the file and calculate the total and average of each column of numbers")
filename= input("\nWhat is the name of the file?")
myfile = open(filename, "r")
with open("numbers.txt") as myfile:
for line in myfile:
parts = line.split()
if len(parts) > 1:
total = sum(parts[0])
total2 = sum(parts[1])
print(total)
print(total2)
main()
您需要使用
float
函数转换字符串。实际上,您并不是在增加total
和total2
,而是在每个值上分配它们
这应该满足您的要求:
def main():
print("This program will read the file and calculate the total and average of each column of numbers")
filename= input("\nWhat is the name of the file?")
myfile = open(filename, "r")
with open("numbers.txt") as myfile:
count = 0
total = 0.0
total2 = 0.0
for line in myfile:
parts = line.split()
if len(parts) > 1:
total += float(parts[0])
total2 += float(parts[1])
count += 1
print(total)
print(total2)
print(total / count)
print(total2 / count)
该错误意味着您无法将字符串(如“1”)添加到数字(如1)中。使用int(“1”)将字符串“1”转换为数字1。从文件中读取数字时,它们的格式为
string
格式。将sum计算更改为int(sum(parts[0])返回的值与此值相同error@Beginner,他必须使用int
将字符串转换为整数,这是正确的,但您的代码是反向的。它应该是sum(int(parts[0]))
@leogama-抓得好!!这是一个愚蠢的错误事实上,split
调用确实处理了尾随的换行:S.split(sep=None,maxslit=-1)->list of strings返回S中的单词列表,使用sep作为分隔符字符串。如果给定maxsplit,则最多执行maxsplit拆分。如果未指定sep或未指定sep,则任何空白字符串都是分隔符,空字符串将从结果中删除。@leogama啊,是的,在这种情况下,split
将执行正确的操作,但它是正确的一个常见的问题,如果你只是从文件中读取一个整数。感谢所有的帮助,我仍然得到错误,ValueError:invalid literal for int(),以10为基数:“12.3”,那么你的数字不是整数,你应该使用float
。我已经更新了我的答案。