打印最高平均值 - “不支持的操作数类型为+:'int'和'str'”
我试图实现从最高到最低打印平均分的输出。但是,当我运行该程序时,出现错误:unsupported operand type(s) for +: 'int' and 'str'
。打印最高平均值 - “不支持的操作数类型为+:'int'和'str'”
我是相当新的Python和我不知道我在哪里出了毛病,这个代码:
f = open('ClassA.txt', 'r')
#a empty dictionar created
d = {}
#loop to split the data in the ext file
for line in f:
columns = line.split(": ")
#identifies the key and value with either 0 or 1
names = columns[0]
scores = columns[1].strip()
#appends values if a key already exists
tries = 0
while tries < 3:
d.setdefault(names, []).append(scores)
tries = tries + 1
if wish == '3':
for names, v in sorted(d.items()):
average = sum(v)/len(v)
print ("{} Scored: {}".format(names,average))
的错误,我得到:
Traceback (most recent call last):
File "N:\task 3 final.py", line 33, in <module>
average = sum(v)/len(v)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
你有串在您的字典,但sum()
将以数字0
开头,以仅累加数值:
>>> sum(['1', '2'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
转换你的分数为数字,无论是int()
或float()
根据您的格式:
scores = int(columns[1].strip())
解决了它,但我遇到了另一个错误。当我print(“{} Scored:{}”。format(names,max(average)))'它出现了'TypeError:'float'对象不可迭代,即使我做'浮动(分数) – 2015-02-10 11:52:48
@PythonPerson:'average'不是一个序列,它是*一个浮点数*。如果你想在多个这样的数字中找到最大值,你将不得不跟踪列表中的数据。 – 2015-02-10 11:54:31
是否有一个函数可以让我从最高到最低打印或者我是否必须创建一个循环来执行此操作? – 2015-02-10 11:57:19
哪条线是给这个错误? – 2015-02-10 11:39:14
回溯(最近一次调用最后): 文件“N:\ task 3 final.py”,第33行,在 average = sum(v)/ len(v) –
2015-02-10 11:41:16
@PythonPerson:你应该[编辑]你的问题添加该信息。 – 2015-02-10 11:41:56