head first python 5


点击(此处)折叠或打开

  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. def filetolist(file,listname):
  4.     try:
  5.         #打开文件
  6.         with open(file) as jaf:
  7.             #读取数据行
  8.             data = jaf.readline()
  9.         #转换成list
  10.         listname=data.strip().split(',')
  11.         return listname
  12.     except IOError as ioerr:
  13.         print('File error : %s' % ioerr)
  14.         return(None)
  15.         
  16. #处理字符,转换成m.s格式
  17. def sanitize(time_string):
  18.     if '-' in time_string:
  19.         splitter = '-'
  20.     elif ':' in time_string:
  21.         splitter = ':'
  22.     else:
  23.         return time_string
  24.     (min, sec) = time_string.split(splitter)
  25.     return (min + '.' + sec)

  26. for name in ["james", "julie", "mikey", "sarah"]:
  27.     thelist=filetolist(name+".txt",name)
  28.     cleanname = 'clean' + name
  29.     cleanname = []
  30.     for each_t in thelist:
  31.         cleanname.append(sanitize(each_t))
  32.     print(sorted(cleanname))
  33.     #使用列表推导式
  34.     print('use list comprehension')
  35.     cleanname2 = [sanitize(each_it) for each_it in thelist]
  36.     print(sorted(cleanname2))
  37.     #使用for 处理
  38. # sorted_name= sorted(cleanname2)
  39. # unique_name = 'unique_' + name
  40. # unique_name = []
  41. # for item in sorted_name:
  42. # if item not in unique_name:
  43. # unique_name.append(item)
  44. # print(unique_name[0:3])
  45.     #使用工厂函数set()
  46.     print(sorted(set(cleanname2))[0:3])
t@localhost 5$ python3 kelly.py
['2.01', '2.01', '2.22', '2.34', '2.34', '2.45', '3.01', '3.10', '3.21']
use list comprehension
['2.01', '2.01', '2.22', '2.34', '2.34', '2.45', '3.01', '3.10', '3.21']
['2.01', '2.22', '2.34']
['2.11', '2.11', '2.23', '2.23', '2.59', '3.10', '3.10', '3.21', '3.21']
use list comprehension
['2.11', '2.11', '2.23', '2.23', '2.59', '3.10', '3.10', '3.21', '3.21']
['2.11', '2.23', '2.59']
['2.22', '2.38', '2.49', '3.01', '3.01', '3.02', '3.02', '3.02', '3.22']
use list comprehension
['2.22', '2.38', '2.49', '3.01', '3.01', '3.02', '3.02', '3.02', '3.22']
['2.22', '2.38', '2.49']
['2.18', '2.25', '2.39', '2.54', '2.55', '2.55', '2.55', '2.58', '2.58']
use list comprehension
['2.18', '2.25', '2.39', '2.54', '2.55', '2.55', '2.55', '2.58', '2.58']
['2.18', '2.25', '2.39']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值