美文网首页程序媛on the way
案例:规范时间序列1

案例:规范时间序列1

作者: Sonia_Du | 来源:发表于2019-03-28 15:27 被阅读0次
    import os
    os.chdir('C:\\Users\\Sonia\\Desktop\\')  #切换文件目录
    
    #将时间转换为mins.secs的格式
    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)
    
    def read(filename,separator = ','):
        try:
            with open(filename,"r") as file:
                data = file.readline()
                lists = data.strip().split(separator)    #方法串链,从左向右对data进行处理
    
            #以下代码可以合并为推导列表①
            #clean_list = []
            #for each_item in lists:
            #    clean_list.append(sanitize(each_item))
            clean_list = [sanitize(each_item) for each_item in lists]       #推导列表①
            print('clean_list:'+str(clean_list))
    
    
            #order_list = sorted(clean_list)②
            order_list = sorted(sanitize(each_item) for each_item in lists)     #推导列表②
            print('order_list:'+str(order_list))
    
    
            #以下代码可以合并为推导列表③
            #unique_list = []
            #for each_item in order_list:
            #   if each_item not in unique_list:
            #        unique_list.append(each_item)
            unique_list =sorted(set(order_list))         #推导列表③
            #如果不加sorted,直接用set会乱序
            unique_list:['2.01', '2.22', '2.34', '2.45', '3.01', '3.10', '3.21']
            unique_list2:{'3.21', '3.01', '2.22', '3.10', '2.01', '2.45', '2.34'}'''
            print('unique_list:'+str(unique_list))
    
    
            #①②③可以合并成推到列表④
            print('推导列表④:'+str(sorted(set(sanitize(each_item) for each_item in lists))))   #推导列表④
            print(unique_list[0:3])
    
        except IOError as err:
            print('File Error:' + str(err))
            return(None)
      
    james = read('james.txt')  
    

    相关文章

      网友评论

        本文标题:案例:规范时间序列1

        本文链接:https://www.haomeiwen.com/subject/bbnqbqtx.html