如何从python中的txt文件按升序排序?

2024-04-19 11:24:26 发布

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

我是python新手,有一个很简单的问题。我有一个包含道路名称和长度的txt文件。i、 东大街56英里。如何用Python调用该文件并按升序对所有道路长度进行排序,让我感到困惑。谢谢你的帮助。你知道吗


Tags: 文件txt名称排序道路新手升序
1条回答
网友
1楼 · 发布于 2024-04-19 11:24:26

假设每个数字后面都有一个“英里”。(这是一个未经测试的代码,因此您可以编辑它,但我认为这个想法是正确的)。你知道吗

编辑:这是测试

import collections
originaldict = {}
newdict = collections.OrderedDict()

def isnum(string):
    try:
        if string is ".":
            return True
        float(string)
        return True

    except Exception:
        return False

for line in open(input_file, "r"):
    string = line[:line.find("miles") - 1]
    print string
    curnum = ""
    for c in reversed(string):
        if not isnum(c):
            break
        curnum = c + curnum
    originaldict[float(curnum)] = []
    originaldict[float(curnum)].append(line)


for num in sorted(originaldict.iterkeys()):
    newdict[num] = []
    newdict[num].append(originaldict[num][0])
    del originaldict[num][0]


with open(output_file, "a") as o:
    for value in newdict.values():
        for line in value:
            o.write(line + "\n")

相关问题 更多 >