目前我正试图通过排序系统来解决一些问题,正如您将对其他问题所说的那样。如果您需要,也可以在那里找到一些信息。
我的问题是,我想要一个整齐排序的分类系统,我似乎已经破坏了。
我有一个txt文件,其中包含以下数据:
Alex 8
约翰4
Reece 7
Alex 8
丽贝卡2
**新的分类方法仍然不起作用**
def sortNumeric(fileName, i, toWrite):
with open(fileName, 'r') as inFile:
pairs = sorted((l.strip().split() for l in inFile),
key=operator.itemgetter(1))
with open(fileName, 'w') as outFile:
outFile.write(os.linesep.join(p[0] + ' ' + p[1] for p in pairs))
它目前将此内容写入文件:
Reece0John
甚至不包括约翰的得分或任何东西! 我需要把它写成文件,如下:
丽贝卡2
约翰3
Reece 7
Alex 8
Alex 8
所以向下而不是在一条线上。对我的分拣系统的任何帮助或改进都将不胜感激。
以防万一我的程序其他部分搞砸了......这就是整个事情!
答案 0 :(得分:1)
不确定替换(和截断)的所有内容是什么..
import os
def mykey(item):
int(item[1])
def sortNumeric(fileName, i, toWrite):
with open(fileName, 'r') as inFile:
pairs = sorted((l.strip().split() for l in inFile),
key=mykey)
with open(toWrite, 'w') as outFile:
outfile.write(os.linesep.join(p[0] + ' ' + p[1] for p in pairs))
作为一个简短的(非文件)示例..
>>> infile = ['Alex 8', 'John 4', 'Reece 7', 'Alex 8', 'Rebbecca 2']
>>> pairs = sorted((l.strip().split() for l in infile),
... key=mykey)
>>> os.linesep.join(p[0] + ' ' + p[1] for p in pairs)
'Rebbecca 2\nJohn 4\nReece 7\nAlex 8\nAlex 8'
>>> print(os.linesep.join(p[0] + ' ' + p[1] for p in pairs))
Rebbecca 2
John 4
Reece 7
Alex 8
Alex 8
>>>
答案 1 :(得分:1)
问题出在这一行:
"\n".join(name_score[0] + " " + name_score[1] for name_score in pairs)
join 的结果未分配给任何内容。
您应该在该行前加pairs =
:
pairs = "\n".join(name_score[0] + " " + name_score[1] for name_score in pairs)
答案 2 :(得分:0)
让整个str()
事情成为,你不需要它:
def sortNumeric(fileName, toWrite):
pairs = [l.strip().split(" ") for l in open(fileName, "r")]
pairs.sort(key = lambda name_score: int(name_score[1]))
f = open(toWrite, "w")
f.write("\n".join(name_score[0] + " " + name_score[1] for name_score in pairs))
f.close()