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

2024-09-30 01:30:57 发布

您现在位置: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]**

Tags: 代码nameintxtdataifliopen
3条回答

你的问题不清楚,换句话说,向字典键中添加多个整数是什么意思?这部分很混乱,因为你的代码

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

似乎意味着您想将字符串(score)添加到整数(int(score))中,这是不可能的。如果要将它们并排添加到一个列表中,这样,给定一个“4”的分数,结果就是['4', 4],那么您所要做的就是将最后几行改成这个。你知道吗

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

另外,eumiro对代码的其他更改也是一个很好的建议,所以如果您不确定这些更改是如何工作的,请记住它们并阅读文档。你知道吗

使diction1保持list。你知道吗

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

文件看起来怎么样?你知道吗

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()}

相关问题 更多 >

    热门问题