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)]
-----------------------------------------------

 

posted @ 2017-09-04 15:27  徐家汇  阅读(7546)  评论(0编辑  收藏  举报