Chapter5-拼接成新的格式并排序

    xiaoxiao2021-12-14  17

    james的跑步时间存储为james.txt,内容如下:

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

    写一个函数,把里面的“-” 和“:”都改为 “ . "

    import os import sys def sanitize(time_string): if '-' in time_string: splitter = '-' elif ':' in time_string: splitter = ':' else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + '.' + secs) #拼接出新的格式 with open('james.txt') as jaf: data = jaf.readline() james = data.strip().split(',') #去掉空白符 clean_james=[] for each_t in james: clean_james.append(sanitize(each_t)) #去掉“-”和“:” james2=sorted(james) print("the_oldlist: " , james) #输出原文 print("Sorted list: " , james2) #输出仅原文排序 print("Correct list: " , sorted(clean_james)) #输出原文去掉“-”和“:”,再排序

    输出结果:

    RESTART: C:/Users/ThinkPad/AppData/Local/Programs/Python/Python36-32/chapter5/chapter5-try.py the_oldlist: ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22'] Sorted list: ['2-22', '2-34', '2.34', '2.45', '2:01', '2:01', '3.01', '3:10', '3:21'] Correct list: ['2.01', '2.01', '2.22', '2.34', '2.34', '2.45', '3.01', '3.10', '3.21'] >>>

    其中打开文件那三行可以抽象出,及其用法和打印不重复的有序头三个时间。

    def get_coach_data(filename): try: with open (filename) as f: data=f.readline() return (data.strip().split(',')) except IOError as ioerr: print("File Error: " + str(ioerr)) return (None) james4=get_coach_data('james.txt') print(sorted(set(sanitize (t) for t in james4))[0:3])

    细节:

    http://www.jianshu.com/p/634136c2e2a2

    转载请注明原文地址: https://ju.6miu.com/read-963568.html

    最新回复(0)