2015-01-21 61 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的其他更改你的代码是很好的建议,所以记住它们,如果你不知道应该如何它的任何作品阅读文档。

相关问题