Python笔记(六):推导数据

(一)  准备工作

创建1个文件记录运动员的跑步成绩

james.txt 

2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22

(二)  要求

在屏幕上输出运动员最好的3个成绩

(三)  思考该怎么实现

(1)通过open()创建文件对象

(2)通过open()的readline方法读取文件数据(这个输出的是一行数据)

(3)想要获取最好的3个成绩,那么首先要将数据分割(通过split分割成绩)

(4)对分割后的列表数据进行排序

(5)2-34,3:21,2.34中间的符号不一致会导致排序出问题(-和,和.),所以还需要一个函数将它们修改成一致的。

(四)  具体实现

(1)   主程序代码

from FirstPython import the_list as tl
#导入the_list模块
the_james = tl.dsfile('F:PythonPython文件james.txt')
#调用the_list模块的dsfile()函数读取文件数据
print(sorted(set([tl.sanitize(t) for t in the_james]),reverse=True)[0:3])
#sorted()默认升序排序,reverse=True时降序排序
#set()删除重复项,返回新的集合对象(无序的)
#[0:3]访问列表第0项、第1项、第2项的数据
'''
[tl.sanitize(t) for t in the_james] 等价于下面的代码(迭代处理the_james列表,返回一个新的列表)
new_list = []
for t in the_james:
    new_list.append(tl.sanitize(t))
'''

(2)    the_list模块代码

def sanitize(time_str):
    #传入数据,将'-'和':'修改为'.'并返回,否则直接返回
   
if '-' in time_str:
        (x,y) = time_str.split('-',1)
        return(x+"."+y)
    elif ':' in time_str:
        (x,y) = time_str.split(':',1)
        return (x + "." + y)
    else:
        return(time_str)

def dsfile(the_file):
    #传入一个文件,返回文件第一行数据
 
with open(the_file) as james_file:
    each_line = james_file.readline().strip().split(',')
    #strip()去除字符串中不需要的空白符,不加这个列表数据会多一个
    #split(',')根据,分割数据,返回一个列表
   
return each_line

 

原文地址:https://www.cnblogs.com/simple-free/p/8401019.html