Skip to main content
 首页 » 编程设计

Python排序文本文件

2024年10月25日9dyllove98

所以我知道如何导入 texfile 并对数字进行排序,例如:

1 
6 
4 
6 
9 
3 
5 

但我不知道如何对看起来像这样的数据进行排序:

Merchant_9976 20122 
Merchant_9977 91840 
Merchant_9978 92739 
Merchant_9979 97252 
Merchant_9980 76885 
Merchant_9981 67835 
Merchant_9982 42201 
Merchant_9983 47463 

到目前为止,这是我的代码

def sort_slow(seq): 
    for i in range(1, len(seq)): 
        j = i 
        while j > 0 and seq[j - 1] > seq[j]: 
            seq[j - 1], seq[j] = seq[j], seq[j - 1] 
            j -= 1 
    return seq 
 
 
def main(): 
    fileName = str(input('Please enter a filename: ')) 
    file = open(fileName) 
    sort1 = [] 
    for lines in file: 
        sort1.append(int(lines.strip())) 
    sort_slow(sort1) 
    print(sort1) 
 
main() 

我对编码比较陌生。*大约 1 个月

请您参考如下方法:

下面将按右列的整数排序

with open('file.txt', 'r') as f: 
    data = f.readlines() 
    sorted_data = sorted(data, key=lambda i: int(i.split()[1])) 
    print(sorted_data) 

或者如果您只是希望它们按商家编号排序

with open('file.txt', 'r') as f: 
    data = f.readlines() 
    sorted_data = sorted(data) 
    print(sorted_data)