Python 迭代删除重复项,集合删除重复项
2015-09-29 16:21
495 查看
1. 迭代删除重复项:先排序列表项,然后通过新迭代(not in)去除重复项,分片打印
2. 集合删除重复项:先set创建集合去除重复项,然后进行排序,分片打印
3.精简代码,创建一个小函数rmspace去除空白符,通过函数调用分片打印
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 jas: data = jas.readline() james=data.strip().split(',') print('before sort and senitize, unique for james',james) james=sorted ([sanitize(t) for t in james]) unique_james=[] for each_t in james: if each_t not in unique_james: unique_james.append(each_t) print('First 3 time for james',unique_james[0:3]) =========== RESTART: C:\Users\eric\Documents\Python\kelly\kelly.py =========== before sort and senitize, unique for james ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22'] First 3 time for james ['2.01', '2.22', '2.34']
2. 集合删除重复项:先set创建集合去除重复项,然后进行排序,分片打印
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 jas: data = jas.readline() james=data.strip().split(',') print('before sort and senitize, unique for james',james) james=sorted (set([sanitize(t) for t in james])) print('First 3 time for james',james[0:3]) =========== RESTART: C:\Users\eric\Documents\Python\kelly\kelly.py =========== before sort and senitize, unique for james ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22'] First 3 time for james ['2.01', '2.22', '2.34']
3.精简代码,创建一个小函数rmspace去除空白符,通过函数调用分片打印
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 rmspace(file): with open(file) as fo: data=fo.readline() return data.strip().split(',') james=rmspace('james.txt') print('before sort and senitize, unique for james',james) print('First 3 time for james',sorted(set([sanitize(t) for t in james]))[0:3]) =========== RESTART: C:\Users\eric\Documents\Python\kelly\kelly.py =========== before sort and senitize, unique for james ['2-34', '3:21', '2.34', '2.45', '3.01', '2:01', '2:01', '3:10', '2-22'] First 3 time for james ['2.01', '2.22', '2.34']
相关文章推荐
- python笔记-调用eval函数出现invalid syntax错误
- python list和tuple相互转化
- 关于Python学习之我见 不断更新
- python 使用全局变量 global
- Python-Open website
- Python中的对象赋值、浅拷贝与深拷贝
- Python Dict 词典的用法
- [转载]python encode和decode函数说明
- python 格式规范工具 autopep8 Tool to convert Python code to be PEP8 compliant
- [转载]Python2.7 urlparse学习
- python——string
- LeetCode----Ugly Number
- Python之下载安装以及第一个例子
- [转载]用python解析html--SGMLParser
- [转载]python模块学习---HTMLParser(解析HTML文档元素)
- 【代码片段】汉诺塔python
- 用python实现远程复制 (scp + expect )
- python中的enumerate
- python实现目录下文件名匹配的进行迁移
- python学习笔记1:python入门