如何对excel工作表键的行进行排序取决于其中一列?

2024-06-16 09:17:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据评分按降序对行进行排序。你知道吗

这是我的excel工作表的当前格式。你知道吗

Minions 2015 6.4
Now You See Me 2013 7.3
Prisoners 2013 8.1
Rumor Has It 1993� 5.4
The Prestige 2006 8.5
The Proposal 2009 6.7

我想要这样的输出:

The Prestige 2006 8.5
Prisoners 2013 8.1
Now You See Me 2013 7.3
The Proposal 2009 6.7
Minions 2015 6.4
Rumor Has It 1993� 5.4

Tags: theyou排序it评分nowmehas
1条回答
网友
1楼 · 发布于 2024-06-16 09:17:14

首先你需要阅读你可以使用readlines()

file = open('thefile.txt', 'r')
fileList=file.readlines()

然后您需要阅读列表中的每个元素:

lines=[]
for i in range(len(fileList)):
    lines.append(fileList[i].split(' '))

并使用itemgetterfrom operator import itemgetter)对“行”进行排序:

Result=sorted(lines, key=itemgetter(2))

然后写一个新文件

所有代码:

from operator import itemgetter


file = open('thefile.txt', 'r')
fileList=file.readlines()

lines=[]
for i in range(len(fileList)):
    lines.append(fileList[i].split(' '))

sortedLines=sorted(lines, key=itemgetter(2))

result=[]

for j in range(len(sortedLines)): 
    result.append(' '.join(sortedLines[j]))


newFile=open("fileSorted.txt", "w")

for j in result: 
    newFile.write("%s\n" % j)

相关问题 更多 >