标签:python3 nbsp image 新建 sort span strip splitter 列表
首先是数据:
将上边的四个数据分别写在新建的txt文件中
1、将txt数据转为列表
with open(‘james.txt‘) as jaf: data = jaf.readline() #读取数据行 james = data.strip().split(‘,‘)#将数据转换为列表 with open(‘julie.txt‘) as jul: data = jul.readline() julie = data.strip().split(‘,‘) with open(‘sarah.txt‘) as sar: data = sar.readline() sarah = data.strip().split()
with open(‘james.txt‘) as jaf, open(‘julie.txt‘) as jul,open(‘sarah.txt‘) as sar: data = jaf.readline() #读取数据行 james = data.strip().split(‘,‘)#将数据转换为列表 data = jul.readline() julie = data.strip().split(‘,‘) data = sar.readline() sarah = data.strip().split() print(james) print(julie) print(sarah)
2、排序:原地排序 james.sort()、复制排序:james2 = james.sorted() 默认升序,降序参数 sort(reverse= True)
由于数据中有-.:, 需要进一步操作
def sanitize(listt): if ‘-‘ in listt: splitter = ‘-‘ elif ‘:‘ in listt: splitter = ‘:‘ else: return (listt) (mine, sece) = listt.split(splitter)# 分裂字符串 结合字符串 return (mine + ‘.‘ + sece) def returnkist(string): with open(string) as jaf: data = jaf.readline() # 读取数据行 james = data.strip().split(‘,‘) # 将数据转换为列表 clean_james = [] for ja in james: clean_james.append(sanitize(ja)) clean_james.sort(reverse=True) return clean_james clean = returnkist(‘james.txt‘) print(clean)
def sanitize(listt): if ‘-‘ in listt: splitter = ‘-‘ elif ‘:‘ in listt: splitter = ‘:‘ else: return (listt) (mine, sece) = listt.split(splitter)# 分裂字符串 结合字符串 return (mine + ‘.‘ + sece) with open(‘james.txt‘) as jaf, open(‘julie.txt‘) as jul,open(‘sarah.txt‘) as sar: data = jaf.readline() #读取数据行 james = data.strip().split(‘,‘)#将数据转换为列表 data = jul.readline() julie = data.strip().split(‘,‘) data = sar.readline() sarah = data.strip().split() clean_james = [] for ja in james: clean_james.append(sanitize(ja)) clean_james.sort() print(clean_james)
标签:python3 nbsp image 新建 sort span strip splitter 列表
原文地址:http://www.cnblogs.com/xujiahui/p/7473819.html