2015-01-21 74 views
-6

這是我的代碼,我需要制定出每個學生的平均分數,但在這部分代碼是incorrect.It是我需要修復的星星部分如何在Python字典中向一個名稱添加多個整數?

while choice == 'av'.lower(): 
    if schClass == '1': 
     schClass = open("scores1.txt", 'r') 
     li = open("scores1.txt", 'r') 
     data = li.read().splitlines() 
     for li in data: 
     name = li.split(":")[0] 
     score = li.split(":")[1] 
     **if name not in diction1: 
      diction1[name] = score 
     elif name in diction1: 
      diction1[name] = int(score) + diction1[name]** 
+2

''av'.lower()'沒用,只是''av''。而elif條件也是無用的,它永遠是真的。無論如何,你實際上沒有告訴我們什麼是錯的? – 2015-01-21 09:16:09

+0

這是最後一行,將一個以上的分數添加到名稱中 – KURUN 2015-01-21 09:17:15

+0

從集合模塊中將'diction1'設置爲'defaultdict(set)'(或'defaultdict(list)',如果需要的話)。 – L3viathan 2015-01-21 09:17:46

回答

-1

diction1保持一list

if name not in diction1: 
    diction1[name] = [score] 
else: 
    diction1[name].append(int(score)) 
+1

'diction1.setdefault(name,[])。append(int(score))' – Kos 2015-01-21 09:21:29

+0

'str'object has no attribute'append' – KURUN 2015-01-21 09:23:07

+0

@KURUN:那是因爲你在裏面放了一個字符串。在字典裏放一個__list__。 – 2015-01-21 09:25:27

0

該文件是怎麼樣的?

A: 10 
B: 10 
A: 20 
B: 12 

A: 10 20 
B: 10 12 

該解決方案可與這兩種格式。

首先,建立名單的字典與所有得分:

all_scores = {} 
while choice == 'av': 
    if schClass == '1': 
     with open("scores1.txt", 'r') as f: 
      for line in f: 
       name, scores = li.split(':', 1) 
       name_scores = all_scores.setdefault(name, []) 
       for score in scores.split(): 
        name_scores.append(int(score)) 

然後計算平均值(轉換總結浮動,以獲得精確的平均值):

averages = {name: float(sum(scores))/len(scores) 
      for name, scores in all_scores.iteritems()} 
+0

AttributeError:'str'對象沒有屬性'追加' – KURUN 2015-01-21 09:42:38

+0

@KURUN:我的代碼中唯一的附加符將應用於列表。該列表將在一個空的字典中初始化。 – eumiro 2015-01-21 09:44:47

+0

第一個,這是第一個,它不能被改變 – KURUN 2015-01-21 09:45:14

0

你的問題目前還不清楚;換句話說,你是什麼意思將一個以上的整數添加到字典鍵?這部分是令人困惑,因爲你的代碼

diction1[name] = int(score) + diction1[name]** 

似乎在暗示你想爲一個字符串(score)添加到一個整數(int(score)),這是不可能的。如果是將它們並排添加到列表中,那麼給定分數'4',結果爲['4', 4],那麼您所要做的就是將最後幾行更改爲此。

if name not in diction1: 
    diction1[name] = [score, int(score)] 

此外,eumiro的其他更改你的代碼是很好的建議,所以記住它們,如果你不知道應該如何它的任何作品閱讀文檔。

相關問題