超快,三十行代码实现python中txt文件读取和分类

先上结果↓

 话不多说,接下来就来看看代码全貌吧

//陈烦烦不说话
def read_data(data_path):
    with open(data_path) as f:
        data=f.read().split(',')
        return data

S_student=read_data('work/stu5.txt')
M_student=read_data('work/stu6.txt')

class Student:
    def __init__(self,name,dob,age,gender,spe,score=[]):
        self.name=name
        self.dob=dob
        self.age=age
        self.gen=gender
        self.spe=spe
        self.score=score
    
class Spostudent(Student):
    def top3(self):
        return sorted(abs(int(t)) for t in self.score)[0:3]

class Artstudent(Student):
    def top3(self):
        return sorted(abs(int(t)) for t in self.score)[-3:]

def Student_pr(stu):
    print('姓名:%s,生日:%s,年龄:%s,性别:%s,分数:%s,特长分:%s'%(stu.name,stu.dob,stu.age,stu.gen,stu.top3(),stu.spe))

stu_5=Spostudent(S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student.pop(0),S_student)
stu_6=Artstudent(M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student.pop(0),M_student)
Student_pr(stu_5)
Student_pr(stu_6)

该代码是在解决这样一个问题:

定义Spostudent、Artstudent为Student的子类,在子类的属性里面新增了spe为特长分数。Spostudent包括的top3方法返回的是最低的3个得分(可重复),Artstudent包括top3方法返回的是最高的3个得分(可重复),最后使用多态的方式输出2个特长同学的姓名、生日、年龄、性别、分数、特长分。

对代码内容的一些讲解:

用到两个函数做封装,可以大大提高运行速度,也方便大家移植

sorted(abs(int(t)) for t in self.score)[0:3]

这句话用到了两个python的内置函数,abs是将负数变为正数的,sorted是将数据排序

 data=f.read().split(',')

这句话就是将文件内容以逗号为分隔符将文件分开,因为我读取的文件是这样子的,如果需要其他形式,如:空格。仅需改为split(' ')

本篇分享到此结束,如果有看不懂的地方欢迎给我留言!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值