Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对excel工作表键的行进行排序取决于其中一列?_Python_Sorting - Fatal编程技术网

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

Python 如何对excel工作表键的行进行排序取决于其中一列?,python,sorting,Python,Sorting,我想根据评分按降序对行进行排序 这是我的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 2

我想根据评分按降序对行进行排序

这是我的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

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

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

lines=[]
for i in range(len(fileList)):
    lines.append(fileList[i].split(' '))
并使用
itemgetter
来自操作员导入itemgetter
)对“行”进行排序:

然后写入一个新文件

所有代码:

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)

数据是如何组织的还不是很清楚,您是以python的列表形式获得的吗?你有一些代码要发布吗?否则在excel中有一个排序功能。但是我们仍然不知道环境,哪个库用于连接到工作表等。请,提供更多详细信息请花些时间阅读,以确保a)您具体说明了您尝试过的内容和遇到的困难,b)我们获得了足够的信息来帮助您。抱歉@Dadep,我正在将每一行存储在列表中,并将其写入.txt文件中。
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)