Skip to main content
 首页 » 编程设计

python之在一行中按升序排列数字

2025年05月04日13tuyile006

所以我在文件中有以下输出(数千行) 输入.txt

2956:1 1076:1 4118:1 1378:1 2561:1  
1039:1 1662:1 
1948:1 894:1 1797:1 1662:1 

问题是我需要让每一行按升序排序

期望的输出: 输出.txt

1076:1 1378:1 2561:1 2956:1 4118:1 
1039:1 1662:1 
894:1 1662:1 1797:1 1948:1 

要做到这一点,这正成为一个真正的挑战,我正在寻找一个 python 函数来为我做这件事。这些行必须保持它们所在的顺序,但每一行都必须按升序排序(就像输出一样)。

关于如何做到这一点有什么想法吗?

请您参考如下方法:

with open('input.txt') as f, open('output.txt', 'w') as out: 
    for line in f: 
        line = line.split()  #splits the line on whitespaces and returns a list 
        #sort the list based on the integer value of the item on the left side of the `:` 
        line.sort(key = lambda x: int(x.split(':')[0])) 
        out.write(" ".join(line) + '\n') 

输出:

1076:1 1378:1 2561:1 2956:1 4118:1 
1039:1 1662:1 
894:1 1662:1 1797:1 1948:1