将文本文件中的数值数据从高到低排序(Python)

时间:2016-01-10 11:47:02

标签: python sorting

我使用Python将各种分数保存到文本文件中。以下是文本文件的结构(文本文件的名称是class_a.txt):

Ben,10
Harry,4
Joe,6
Adam,7
Anthony,10

我已设法按字母顺序对分数进行排序,以下是代码:

def alpha():
    if class_name == "a":
        with open("class_a.txt") as f:
            lines = f.readlines()
            lines = sorted(lines)
            for line in lines:
                name = line[:line.find(",")]
                marks = line[line.find(",")+1:].split(",")
                marks = sorted(marks)
                print(name + "'s Score = " + marks[-1])

此代码输出如下分数:

Adam's Score = 7    
Anthony's Score = 10    
Ben's Score = 10    
Harry's Score = 4   
Joe's Score = 6

但是我还想添加一个选项,将分数从最高到最低排序。

例如,当Python从文本文件输出数据时,它将如下所示:

Anthony's Score = 10    
Ben's Score = 10    
Adam's Score = 7    
Joe's Score = 6 
Harry's Score = 4

2 个答案:

答案 0 :(得分:3)

这是一种更好的方式来实现你所追求的目标:

import os

path = "D:\\myfolder"

for root, dirs, files in os.walk(path):
    print "root:", root
    for file in files:
        print "-", file

输出:

import csv

with open("class_a.txt") as file:
    csv_reader = csv.reader(file)
    sorted_list = sorted(csv_reader, key=lambda row: int(row[1]), reverse=True)

for name, score in sorted_list:
    print("{0}'s Score = {1}".format(name, score))

通过使用Ben's Score = 10 Anthony's Score = 10 Adam's Score = 7 Joe's Score = 6 Harry's Score = 4 模块,您可以为文件中的每一行生成一个数组,并使用csv对基于特定列生成的列表进行排序。

答案 1 :(得分:2)

你只需要:

def alpha():
    if class_name == "a":
        with open("class_a.txt") as f:
            lines = sorted([i.strip().split(',') for i in f], 
                           key=lambda x: (-int(x[1]), x[0]),
                           reverse=True)

            for name, score in lines:
                 print(name + "'s Score = " + score)

演示:

Anthony's Score = 10
Ben's Score = 10
Adam's Score = 7
Joe's Score = 6
Harry's Score = 4