2015-02-10 95 views
-2

我試圖實現從最高到最低打印平均分的輸出。但是,當我運行該程序時,出現錯誤: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' 
+0

哪條線是給這個錯誤? – 2015-02-10 11:39:14

+0

回溯(最近一次調用最後): 文件「N:\ task 3 final.py」,第33行,在 average = sum(v)/ len(v) – 2015-02-10 11:41:16

+0

@PythonPerson:你應該[編輯]你的問題添加該信息。 – 2015-02-10 11:41:56

回答

1

你有在您的字典,但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()) 
+0

解決了它,但我遇到了另一個錯誤。當我print(「{} Scored:{}」。format(names,max(average)))'它出現了'TypeError:'float'對象不可迭代,即使我做'浮動(分數) – 2015-02-10 11:52:48

+0

@PythonPerson:'average'不是一個序列,它是*一個浮點數*。如果你想在多個這樣的數字中找到最大值,你將不得不跟蹤列表中的數據。 – 2015-02-10 11:54:31

+0

是否有一個函數可以讓我從最高到最低打印或者我是否必須創建一個循環來執行此操作? – 2015-02-10 11:57:19

相關問題