pyrhon程序问题

img

filename = "score.csv"
scores = {"程序设计": [], "体育": [], "经济学": []}

try:
with open(filename, "r") as file:
reader = csv.reader(file)
next(reader) # 跳过文件的第一行(表头)

    for row in reader:
        if len(row) == 4:  # 确保每行都有三个成绩
            _, score1, score2, score3 = row
            scores["程序设计"].append(int(score1))
            scores["体育"].append(int(score2))
            scores["经济学"].append(int(score3))

for subject, subject_scores in scores.items():
    average_score = sum(subject_scores) / len(subject_scores)
    max_score = max(subject_scores)
    min_score = min(subject_scores)

    print(f"科目: {subject}")
    print(f"平均分: {average_score:.2f}")
    print(f"最高分: {max_score}")
    print(f"最低分: {min_score}")
    print()

直接用pandas去取csv文件的方式是最简单的,通过列索引就可以把数据给过滤出来,然后转化成列表,然后再求平均分、最高分、最低分。


import pandas as pd
# scores = {'程序设计': [], '体育': [], '经济学': []}
scores = {}

df = pd.read_csv('score.csv', encoding='utf-8')  # 如果字符编码gbk的,需要把 utf-8 改成 gbk
scores['程序设计'] = df['程序设计'].to_list()
scores['体育'] = df['体育'].to_list()
scores['经济学'] = df['经济学'].to_list()

for k,v in scores.items():
    print( '{}的平均分:{},最高分:{},最低分:{}'.format( k,   round(sum(v) / len(v), 2), max(v), min(v)  ) )

img

  • 以下回答由chatgpt基于相关博客总结生成:

    问题回答:

    在定义字典变量时,需要注意的是确保键的唯一性,不能有重复的键;还需要确保对应的值具有相同的数据结构,例如在本问题里,需要确保三个键值对应的值都是空列表。

    下面是具体的代码实现:

    scores = {'程序设计': [], '体育': [], '经济学': []}
    

    如果需要优化,可以考虑将字典的定义和初始化分开写,例如:

    scores = {}
    keys = ['程序设计', '体育', '经济学']
    for key in keys:
        scores[key] = []
    

    这样可以提高代码的可读性和可维护性。

啥破代码有try没catch都不全的
先把代码好好的都粘代码块里粘全了,再把到底什么问题描述清楚