按列对列表进行排序

时间:2016-01-13 14:50:31

标签: python file sorting fwrite enumerate

目前我正在尝试使用以下数据对文件进行排序:

[Name] [Score]  
[Name] [Score]  

这一切都在继续。我想按分数对它进行排序。所以我的方法是从文件中获取所有数据并对其进行排序。但是我使用sort函数,它将所有数据都放在这种格式中:

[Name] [Score] [Name] [Score]  

我希望它是:

[Name] [Score]  
[Name] [Score]  

然后将其写入文件

def fileWrite(fName, fClass):
    fileName = "%s %s" %(fClass, ".txt")
    fileName = fileName.replace(" ", "")
    return(fileName)

def fileSort(fName, fClass):
    fSort = open(fName, "a+")
    contents = []
    i = getFileData(fName)
    for getData in range(i):
        data1 = fSort.readline()
        replaceWith = "%s %s" %(fClass, ";")
        data1 = data1.replace(fClass, replaceWith)
        contents.append(data1)
    contents.sort()
    print contents
    fSort.truncate(0)
    fSort.write(contents)

def getFileData(fName):
    i = 0
    with open(fName) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

以下是我需要排序的文件中的一些数据:

Reece 10
John 4
Alex 7
Alex 8
John 4
Alex 6
Reece 9

3 个答案:

答案 0 :(得分:4)

您可以先将数据加载成对,如下所示:

pairs = [l.strip().split(' ') for l in open('data.txt', 'r')]    

现在你可以这样排序:

pairs.sort(key = lambda name_score: int(name_score[1]))

最后,您可以将它们更改为如下字符串:

'\n'.join(name_score[0] + ' ' + name_score[1] for name_score in pairs)

您只需open一个文件,write此字符串就可以了。

答案 1 :(得分:3)

您应该尝试pandas

你的python很容易安装pandas。首先,您可能需要安装它 - pip install pandaseasy_install pandas - 您需要python-setuptools。使用sudo apt-get install python-setuptools安装它们。

import pandas
# Read your file as a dataframe in Pandas.
# "sep" is your delimiter "header" row index are options
myData = pandas.read_csv("/path/to/file.txt",sep=",",header=0)
# Now sort with your column key 
sortData = myData.sort(['score'])
# Write out your dataframe to csv
sortData.to_csv("/path/to/output.txt",sep=",",index=False,header=True)

我还没试过这个数据 - 在某个档案中file.txt

name,score
Reece,10
John,4
Alex,7
Alex,8
John,4
Alex,6
Reece,9

输出 -

name,score
John,4
John,4
Alex,6
Alex,7
Alex,8
Reece,9
Reece,10

编辑:标题索引更改为0而不是1

答案 2 :(得分:1)

这样做,

获取文件内容:

with open(yourfile, "r") as f:
    data = [l.split(" ") for l in f]

对它进行排序:

sortedList = sort(data, key=lambda x: int(x[1]))

或使用itemgetter

import operator
sortedList = sort(data, key=operator.itemgetter(1))
相关问题