[英]Sorting txt lines numerically
I took txt file as input and i want to sort them numerically.我将 txt 文件作为输入,我想对它们进行数字排序。 How can i do?
我能怎么做? The input file as txt:
输入文件为txt:
65 1 Hello
78 3 up
78 2 what's
65 2 world
i want the output as:我希望 output 为:
message 1:
65 1 Hello
65 2 world
message 2:
78 2 what's
78 3 up
First i need to sort first numbers, then i need to sort second numbers.首先我需要对第一个数字进行排序,然后我需要对第二个数字进行排序。 I thought i can put every line in a list and then sort them.
我想我可以把每一行放在一个列表中,然后对它们进行排序。 Then i need to write "message n:" before every text group.
然后我需要在每个文本组之前写“消息 n:”。 Finally i need to put them in a new txt file.
最后我需要把它们放在一个新的 txt 文件中。
you can use List.sorted:你可以使用 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 Output
IF you have to sort first in descending order using first-row value and then in ascending using the second-row value如果您必须首先使用第一行值按降序排序,然后使用第二行值按升序排序
This can be done by assigning negative to the second number这可以通过将负数分配给第二个数字来完成
# 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: Output:
You can sort them after splitting into separate lines by 1st and second order numbers as:您可以在按一阶和二阶编号拆分为单独的行后对它们进行排序,如下所示:
sorted([line.split() for line in file_contents.split('\n')], key = lambda x:(int(x[0]), int(x[1])))
results in:结果是:
[['65', '1', 'Hello'],
['65', '2', 'world'],
['78', '2', "what's"],
['78', '3', 'up']]
Then you can play around with this list to have output to your liking: Hint.然后你可以玩这个列表来让 output 符合你的喜好:提示。 Go grab the unique 0th index values and change the message number when 0th index is changed.
Go 获取唯一的第 0 索引值,并在第 0 索引更改时更改消息编号。 While it is unchanged concat all 2nd index values.
虽然它没有改变连接所有第二个索引值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.