Head First Python-python面向对象
1.Python的命令模式和交互模式2.Python笔记3.浅析python中的装饰器decorator4.Python网络编程-Socket简单通信(及python实现远程文件发送)5.python中的*args和**kw6.Python脚本之安装linux源码包-Jenkins7.Python 数据处理库pandas教程(最后附上pandas_datareader使用实例)8.Python 机器学习库 NumPy 教程9.Flask(python)异步(ajax)返回json格式数据10.Python爬虫之urllib-登录博客园11.(转载)python调用shell命令之os 、commands、subprocess
12.Head First Python-python面向对象
13.Head First Python-Python简单处理文件14.Head First Python-Python中与文件相关的操作-读、处理、写15.Python3实现自动查询成绩(主要使用的包有Tesseract-OCR、PIL、execjs、pytesseract、BeautifulSoup)16.Python数据挖掘之随机森林17.Python 绘图库Matplotlib入门教程与大多数其他的编程语言一样,Python容许创建并定义面向对象的类,类可以将代码与代码处理的数据相关联。
对于更加复杂的数据,一般的列表已经不能满足需求了。
我们可以使用字典dict将数据值与键相关联。
1,使用dict来完成处理
相关处理代码如下:
#DICT def sanitize(time_string): if '-' in time_string: spliter='-' elif ':' in time_string: spliter=':' else: return time_string (mins,secs)=time_string.split(spliter) return mins+'.'+secs def get_coach_data(filename): james_data = {} try: with open(filename) as f: data=f.readline() temp_data=data.strip().split(',') #f_data=[sanitize(i) for i in temp_data] james_data = {'Name':temp_data.pop(0),'Bir':temp_data.pop(0),'Times':str(sorted([sanitize(i) for i in temp_data])[0:3])} return james_data except IOError as Ierror: print('read file error: '+str(Ierror)) return None james=get_coach_data('./data/james2.txt') print(james['Name']+"'s fastest times are: "+james['Times'])
2,使用python类:
在面向对象的世界里,代码通常称为类的方法,数据通常称为类的属性。实例化数据对象通常称为实例。
#class class Athlete(object): def __init__(self,name,bir=None,times=[]): self.name=name self.bir=bir self.times=times def top3(self): return sorted(set([sanitize(i) for i in self.times]))[0:3] def add_time(self,a_time): self.times.append(a_time) def add_times(self,b_time): self.times.extend(b_time) def sanitize(time_string): if '-' in time_string: spliter='-' elif ':' in time_string: spliter=':' else: return time_string (mins,secs)=time_string.split(spliter) return mins+'.'+secs def get_coach_data(filename): try: with open(filename) as f: data=f.readline() temp_data=data.strip().split(',') return Athlete(temp_data.pop(0),temp_data.pop(0),temp_data) except IOError as ioerror: print('file open fail:' + str(ioerror)) return None james=get_coach_data('./data/james2.txt') james.add_times(['1-1','1:2']) print(james.name+"'s fastest times are: "+str(james.top3()))
如果你真心觉得文章写得不错,而且对你有所帮助,那就不妨小小打赏一下吧,如果囊中羞涩,不妨帮忙“推荐"一下,您的“推荐”和”打赏“将是我最大的写作动力!
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接.


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?