Python:如何将文本文件中的整数按升序和/或降序排序? [英] Python: How do i sort integers in a text file into ascending and/or descending order?

查看:1120
本文介绍了Python:如何将文本文件中的整数按升序和/或降序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件(data.txt),其中包含名称和得分1:1,即:

I have a text file(data.txt) containing names and scores 1:1 i.e.:

Mike = 1\n John = 2\n Cam = 3\n

我想按升序和降序对整数和相应的名称进行排序.

I want to sort the integers along with the corresponding name in ascending and descending order.

with open(filepath, 'r') as file:
    list = []
    for line in file:
        list.append(line[1:-1].split(","))
list.sort(key=lambda x: int(x[4]))

是的,我已经做过一些研究,但是没有用,我希望你们中的一个可以帮助我修复上面的代码.我知道我必须将文本文件中的数据转换为列表,然后对列表进行排序,然后再写回文本文件,但是我不确定如何做. 来源:如何对文本文件进行数字排序最高还是最低?

Yes, i have done some research however it doesn't work, i was hoping one of you guys could help me fix the code above. I know i must convert the data within the text file into a list then sort the list then put write back to the text file, but i am not sure how. Source: How do i sort a text file numerically highest to lowest?

推荐答案

下面是一个示例,使用sorted()函数在内存中进行.

Here's an example, doing it in memory using the sorted() function.

with open(filepath, 'r') as file:
    sorted_data=sorted(file.readlines(), 
                       key=lambda item: int(item.rsplit('=',1)[-1].strip()))

sorted_data将包含已排序行的列表.

sorted_data will then contain a list of the sorted rows.

这里是:

打开文件:

with open(filepath, 'r') as file:

获取文件的所有行(作为列表):

Get all the lines of the file (as a list):

file.readlines()

对于文件中的每一行,sorted()将根据将每一行传递到键"函数的输出来对它们进行数字排序.

For each line in the file, sorted() will numerically sort them based on the output of passing each line into the "key" function.

键"函数使用一行,将其用"="符号分隔,然后采用该行的最后一部分(=符号后的部分),去除任何前导或尾随空格(.strip()),然后返回强制转换为整数(int)的值.

The "key" function takes a line, splits it by the "=" symbol, then takes the last part of that (the part after the = sign), strips any leading or trailing whitespace (.strip()) and returns the value cast to an integer (int) .

Sorted接受各行并使用键功能输出的数字对其进行排序.

Sorted takes the lines and orders them using the numbers output by the key function.

这篇关于Python:如何将文本文件中的整数按升序和/或降序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆