簡體   English   中英

對 txt 行進行數字排序

[英]Sorting txt lines numerically

我將 txt 文件作為輸入,我想對它們進行數字排序。 我能怎么做? 輸入文件為txt:

65 1 Hello
78 3 up
78 2 what's
65 2 world

我希望 output 為:

message 1:
    65 1 Hello
    65 2 world
message 2:
    78 2 what's
    78 3 up

首先我需要對第一個數字進行排序,然后我需要對第二個數字進行排序。 我想我可以把每一行放在一個列表中,然后對它們進行排序。 然后我需要在每個文本組之前寫“消息 n:”。 最后我需要把它們放在一個新的 txt 文件中。

你可以使用 List.sorted:

# Using readlines() 
file1 = open('./mytext.txt', 'r') 
Lines = file1.readlines() 
  

Lines.sort(key=lambda line: (int(line.split(" ")[0]),int(line.split(" ")[1])),reverse=False)


print(Lines)



temp=0
count=0
for i in Lines:
    value = int(i.split(" ")[0])
    if(value!=temp):
        count+=1
        print("message {0}:".format(count))
        print("    "+(i).replace("\n",""))
        temp=value
    else:
        print("    "+(i).replace("\n",""))
        temp=value
        

Output

在此處輸入圖像描述

如果您必須首先使用第一行值按降序排序,然后使用第二行值按升序排序

這可以通過將負數分配給第二個數字來完成

# Using readlines() 
file1 = open('./mytext.txt', 'r') 
Lines = file1.readlines()   

Lines.sort(key=lambda line: (int(line.split(" ")[0]),-int(line.split(" ")[1])),reverse=True)
    
print(Lines)    

temp=0
count=0
for i in Lines:
    value = int(i.split(" ")[0])
    if(value!=temp):
        count+=1
        print("message {0}:".format(count))
        print("    "+(i).replace("\n",""))
        temp=value
    else:
        print("    "+(i).replace("\n",""))
        temp=value

Output:

在此處輸入圖像描述

您可以在按一階和二階編號拆分為單獨的行后對它們進行排序,如下所示:

sorted([line.split() for line in file_contents.split('\n')], key = lambda x:(int(x[0]), int(x[1])))

結果是:

[['65', '1', 'Hello'],
 ['65', '2', 'world'],
 ['78', '2', "what's"],
 ['78', '3', 'up']]

然后你可以玩這個列表來讓 output 符合你的喜好:提示。 Go 獲取唯一的第 0 索引值,並在第 0 索引更改時更改消息編號。 雖然它沒有改變連接所有第二個索引值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM