python经典百题之分数评级

题目:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

方案一:使用if语句判断

  1. 使用Python内置的open()函数打开txt文件,使用read()方法读取文件中的内容,使用splitlines()方法分割每一行
  2. 遍历每一行,对每一个学生分数进行判断,根据分数划分为A、B、C三类,将评级结果拼接到每一行末尾
  3. 将评级后的内容使用write()方法写回txt文件

优点:实现简单,易于理解

缺点:代码可读性差,当判断条件多且复杂时,代码量会增加,难以维护

with open('scores.txt', 'r') as f:
    lines = f.readlines()  # 读取所有行

with open('scores.txt', 'w') as f:
    for line in lines:
        score = int(line.strip())  # 去除换行符并转为整数
        if score >= 90:
            level = 'A'
        elif score >= 60:
            level = 'B'
        else:
            level = 'C'
        f.write('{} {}\n'.format(line.strip(), level))  # 写入原始分数和评级
 

方案二:使用列表推导式和lambda函数

  1. 使用Python内置的open()函数打开txt文件,使用read()方法读取文件中的内容,使用splitlines()方法分割每一行
  2. 遍历每一行,使用列表推导式和lambda函数对每一个学生分数进行判断,根据分数划分为A、B、C三类,将评级结果拼接到每一行末尾
  3. 将评级后的内容使用write()方法写回txt文件

优点:代码简洁,可读性高,适合进行一些简单的数据操作

缺点:当判断条件复杂时,可读性会下降,不易维护

# lambda函数用于将数值转换成对应的等级
get_grade = lambda score: 'A' if score >= 90 else ('B' if score >= 60 else 'C')

with open('scores.txt', 'r') as f:
    # 读取每一行并根据空格分割成列表
    scores = [line.strip().split() for line in f.readlines()]

# 将每个学生的成绩转换成对应的等级,并将结果追加到列表中
grades = [[*score, get_grade(int(score[-1]))] for score in scores]

with open('grades.txt', 'w') as f:
    # 将每个学生的信息写入文件中
    for grade in grades:
        f.write(' '.join(grade) + '\n')
 

方案三:使用pandas库进行数据处理

  1. 使用pandas库的read_csv()方法读取txt文件
  2. 使用apply()方法将对每一个学生分数进行判断,根据分数划分为A、B、C三类,将评级结果添加到一个新的列中
  3. 将处理后的数据使用to_csv()方法写回txt文件

优点:pandas库具有强大的数据处理能力,可以快速高效地进行数据操作,代码可读性高

缺点:对于简单的数据操作,使用pandas库有些过于复杂,且需要安装第三方库pandas

import pandas as pd

# 读取txt文件,假设文件中有两列,分别为name和score
df = pd.read_table('data.txt', sep='\s+', header=None, names=['name', 'score'])

# 定义评级函数
def get_grade(score):
    if score >= 90:
        return 'A'
    elif score >= 60:
        return 'B'
    else:
        return 'C'

# 添加评级列
df['grade'] = df['score'].apply(get_grade)

# 根据评级列进行排序
df.sort_values(by=['grade'], ascending=False, inplace=True)

# 将结果写入txt文件
df.to_csv('result.txt', index=False, sep='\t', header=None)
 

猜你喜欢

转载自blog.csdn.net/yechuanhui/article/details/132899984