在上一节从零学python系列之数据处理编程实例(一)的基础上数据发生了变化,文件中除了学生的成绩外,新增了学生姓名和出生年月的信息,因此将要成变成:分别根据姓名输出每个学生的无重复的前三个最好成绩和出生年月
数据准备:分别建立四个文本文件
james2.txt James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22
julie2.txt Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21
mikey2.txt Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38
sarah2.txt Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55
在上一节基础上,修改部分代码,将新要求实现如下:
import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\hfpy_code\chapter6') #将工作空间修改为文件所在的目录
#定义函数get_filedata从文件中取值
def get_filedata(filename):
try:
with open(filename) as f: #with语句打开和自动关闭文件
data=f.readline() #从文件中逐行读取字符
data_list=data.strip().split(',') #将字符间的空格清除后,用逗号分隔字符
return({
"name" : data_list.pop(0),
"date_of_birth" : data_list.pop(0),
"times" : str(sorted(set([modify_time_format(s) for s in data_list]))[0:3])
}) #使用字典将关联的姓名,出生年月,时间键和值进行存储并返回
except IOError as ioerr:
print ('File Error' + str(ioerr)) #异常处理,打印错误
return (None)
#定义函数modify_time_format将所有文件中的时分表达方式统一为“分.秒”
def modify_time_format(time_string):
if "-" in time_string:
splitter="-"
elif ":" in time_string:
splitter=":"
else:
splitter="."
(mins, secs)=time_string.split(splitter) #用分隔符splitter分隔字符后分别存入mins和secs
return (mins+ '.' +secs)
#定义函数get_prev_three返回文件中排名前三的不重复的时间成绩
def get_prev_three(filename):
new_list=[modify_time_format(each_t) for each_t in get_filedata(filename)] #采用列表推导将统一时分表达方式后的记录生成新的列表
delete_repetition=set(new_list) #采用集合set函数删除新列表中重复项,并生成新的集合
in_order=sorted(delete_repetition) #采用复制排序sorted函数对无重复性的新集合进行排序
return (in_order[0:3])
#输出james的排名前三的不重复成绩和出生年月
james = get_filedata('james2.txt')
print (james["name"]+"'s fastest times are: " + james["times"])
print (james["name"] + "'s birthday is: " + james["date_of_birth"])
#输出julie的排名前三的不重复成绩和出生年月
julie = get_filedata('julie2.txt')
print (julie["name"]+"'s fastest times are: " + julie["times"])
print (julie["name"] + "'s birthday is: " + julie["date_of_birth"])
#输出mikey的排名前三的不重复成绩和出生年月
mikey = get_filedata('mikey2.txt')
print (mikey["name"]+"'s fastest times are: " + mikey["times"])
print (mikey["name"] + "'s birthday is: " + mikey["date_of_birth"])
#输出sarah的排名前三的不重复成绩和出生年月
sarah = get_filedata('sarah2.txt')
print (sarah["name"]+"'s fastest times are: " + sarah["times"])
print (sarah["name"] + "'s birthday is: " + sarah["date_of_birth"])
通过建立继承内置list的类AthleteList,将方法定义在类中实现相同功能:
import os
print(os.getcwd())
os.chdir('C:\Python33\HeadFirstPython\hfpy_code\chapter6') #将工作空间修改为文件所在的目录
#定义类AthleteList继承python内置的list
class AthleteList(list):
def __init__(self, name, dob=None, times=[]):
list.__init__([])
self.name=name
self.dob=dob
self.extend(times)
def get_prev_three(self):
return (sorted(set([modify_time_format(t) for t in self]))[0:3])
def get_filedata(filename):
try:
with open(filename) as f: #with语句打开和自动关闭文件
data=f.readline() #从文件中逐行读取字符
data_list=data.strip().split(',') #将字符间的空格清除后,用逗号分隔字符
return(
AthleteList(data_list.pop(0), data_list.pop(0), data_list)
) #使用字典将关联的姓名,出生年月,时间键和值进行存储并返回
except IOError as ioerr:
print ('File Error' + str(ioerr)) #异常处理,打印错误
return (None)
def modify_time_format(time_string):
if "-" in time_string:
splitter="-"
elif ":" in time_string:
splitter=":"
else:
splitter="."
(mins, secs)=time_string.split(splitter) #用分隔符splitter分隔字符后分别存入mins和secs
return (mins+ '.' +secs)
james = get_filedata('james2.txt')
print (james.name+"'s fastest times are: " + str(james.get_prev_three()))
julie = get_filedata('julie2.txt')
print (julie.name+"'s fastest times are: " + str(julie.get_prev_three()))
mikey = get_filedata('mikey2.txt')
print (mikey.name+"'s fastest times are: " + str(mikey.get_prev_three()))
sarah = get_filedata('sarah2.txt')
print (sarah.name+"'s fastest times are: " + str(sarah.get_prev_three()))

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)