如何对特定数据/列上的整个文件进行排序?

2024-09-29 19:20:50 发布

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

[数据.txt]

CODE\tUSERNAME\tSPENT\tCOLUM1\tCOLUM2

我想对文件[data.txt]进行排序,使用“spend”。我该怎么做


Tags: 文件数据txtdata排序codespendtusername
2条回答
 def subMenu_5():

    # read file into array of lines
    lines = open("database").readlines()

    # sort those lines using a lambda
    lines.sort(key = lambda line : line.split("\t")[3])

    clientList = []
    dataQuantify = 0
    database = open('database','r')
    i = 1
    while (i == 1):
        if (database.readline() == ''):
            i = 0
        else:
            dataQuantify = dataQuantify + 1
    database.close()


    sortList = open("sortList","w")
    for i in range (3):
        sortList.write(lines[i])
    sortList.close()

    print "[Código] [Nome] [Quant. Prod. Comprados] [Valor Gasto] [Descontos] \n"
    sortList   = open('sortList','r')
    i = 0
    while (i < dataQuantify):
        clientList.append(sortList.readline())
        print clientList[i]
        i = i + 1
    database.close()
    raw_input("Precione 'ENTER' para voltar ao menu principal... ")
    return

这工作!非常感谢

是的,当然有可能。例如:

# read file into array of lines
lines = open("data.txt").readlines()

# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[2])

lambda从要用作排序键的行中挤出SPENT

相关问题 更多 >

    热门问题