对txt行进行数字排序

2024-09-30 16:40:45 发布

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

我把txt文件作为输入,我想对它们进行数字排序。我该怎么办? 输入文件为txt:

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

我希望输出为:

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

首先我需要对第一个数字进行排序,然后我需要对第二个数字进行排序。我想我可以把每一行都列在一个列表中,然后对它们进行排序。然后我需要在每个文本组之前写“messagen:”。最后,我需要把它们放在一个新的txt文件中


Tags: 文件文本txtmessagehello列表world排序
2条回答

您可以在按一阶和二阶编号拆分为单独的行后对其进行排序,如下所示:

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']]

然后,你可以玩这个列表,有你喜欢的输出!提示:获取唯一的第0个索引值,并在第0个索引更改时更改消息编号。而它在所有第二个索引值处保持不变

您可以使用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
        

输出

enter image description here

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

这可以通过将负数指定给第二个数字来实现

# 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

输出:

enter image description here

相关问题 更多 >