Python3 将txt数据转换成列表,进行排序,筛选
Python 程序员需要知道的 30 个技巧
首先是数据:
将上边的四个数据分别写在新建的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)
3、要返回前三名的成绩
在
def returnkist(string):
with open(string) as jaf:
data = jaf.readline() # 读取数据行
james = data.strip().split(',') # 将数据转换为列表
clean_james = [sanitize(s) for s in james]
clean_james.sort(reverse=True)
return [clean_james[a] for a in range(3)]
-----------------------------------------------