如何在python字典中向名称添加多个整数?

如何在python字典中向名称添加多个整数?,python,dictionary,Python,Dictionary,这是我的代码,我需要计算出每个学生的平均分数,但这部分代码是不正确的。我需要修正的是有星星的部分 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: nam

这是我的代码,我需要计算出每个学生的平均分数,但这部分代码是不正确的。我需要修正的是有星星的部分

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]**
使措辞保持一致


文件看起来怎么样

A: 10
B: 10
A: 20
B: 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()}

你的问题不清楚;换句话说,向字典键添加多个整数意味着什么?这一部分令人困惑,因为您的代码

diction1[name] = int(score) + diction1[name]**
似乎暗示您希望将字符串分数添加到整数intscore,这是不可能的。如果要将它们并排添加到一个列表中,这样,如果分数为'4',结果为['4',4],那么您所要做的就是将最后几行更改为这一行

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

此外,eumiro对您的代码所做的其他更改都是很好的建议,因此,如果您不确定其中任何一项的工作原理,请记住这些更改并阅读文档。

'av'。lower没有用,它只是'av'。而elif条件也是无用的,它永远是真的。无论如何,你还没有告诉我们出了什么问题?这是最后一行,在名称中添加多个分数。如果你需要集合模块的订单,请将diction1设置为defaultdictset或defaultdictlist。你需要声明默认diction1分数是多少?一串列表只有一个整数?diction1.setdefaultname,[]。appendintscore'str'对象没有属性'append'@KURUN:这是因为您在其中放入了一个字符串。把一个列表放在dict里面。@KURUN:阅读到python文档发布的链接。我不是保姆。AttributeError:“str”对象没有属性“append”@KURUN:我代码中唯一的append将应用于列表。此列表将初始化为一个空的dict.top列表,这是第一个列表,无法更改。属性错误:“str”对象没有属性“append”,我不知道这是什么means@KURUN:您正在应用。附加到str对象。我的密码里没有。
diction1[name] = int(score) + diction1[name]**
if name not in diction1:
    diction1[name] = [score, int(score)]