Python的新行是sort list issu

2024-04-19 16:28:51 发布

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

目前,我正试图用分类系统解决一些问题,正如你将要回答我的其他问题一样。如果你需要的话,你可以在那里找到一些信息。在

我的问题是,我想要一个整齐有序的分类系统,我似乎已经破坏了。在

我有一个txt文件,其中包含以下数据:
亚历克斯8
约翰四世
锐斯7号
亚历克斯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))    

它当前将此写入文件:

约翰

甚至连约翰的分数都没有!
我需要这样写进文件:

丽贝卡2
约翰3
锐斯7号
亚历克斯8
亚历克斯8

所以向下走,而不是在一条线上。任何对我的分拣系统的帮助或改进都将不胜感激。在

万一我的程序搞砸了。。。整件事都在这儿!在

code


Tags: 文件in信息for系统aswith分类
3条回答

不知道这些替换(和截断)是为了什么。。在

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))

作为一个简短的(非文件)示例。。在

^{pr2}$

就让整个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()

问题在于:

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

由于连接的结果没有分配给任何对象。在

您应该在该行前面加上pairs =

^{pr2}$

相关问题 更多 >