python升序和降序排序,Python:如何将文本文件中的整数按升序和/或降序排序?...

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?

解决方案

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 will then contain a list of the sorted rows.

Here it is:

open the file:

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

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

file.readlines()

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

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 takes the lines and orders them using the numbers output by the key function.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值