2015-12-22 11:14

python：按每一行最后一个数字的从大到小来给全部行排序，怎么实现？

a.txt内容如下。xx为汉字。若最后一个数字相同，则按每一行第一个数字为准从小到大排序
2877,xx,xx,xx,xx,xx,xx,10
2878,xx,xx,xx,xx,xx,1264
2880,xx,xx,xx,xx,xx,xx,6
2881,xx,xx,xx,xx,xx,xx,xx,248
2882,xx,1
2885,xx,xx,xx,xx,1

2886,xx,xx,xx,xx,5
2887,xx,xx,xx,1

2878,xx,xx,xx,xx,xx,1264
2881,xx,xx,xx,xx,xx,xx,xx,248
2877,xx,xx,xx,xx,xx,xx,10
2880,xx,xx,xx,xx,xx,xx,6
2886,xx,xx,xx,xx,5
2882,xx,1
2885,xx,xx,xx,xx,1
2887,xx,xx,xx,1

with open("a.txt",'r+') as fhand:
for line in fhand:
linelist = line.strip('\n').split(',')
lst = list(linelist[-1])
s = sorted(lst,key=lambda last_element : last_element[-1], reverse=True)
print(s6)

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

2条回答默认 最新

• 微wx笑 2015-12-22 11:21
点赞 打赏 评论
• python_tty 2016-01-09 04:36

-*- coding:utf-8 -*-

rest = []
with open('spam.txt') as f:
for line in f:
linelist = line.strip('\n').split(',')
line_rest = []
for item in linelist:
line_rest.append(int(item))
rest.append(line_rest)
re_rest = sorted(rest, key=lambda x: x[-1],reverse=True)

with open('b.txt','w') as fb:
for item in re_rest:
item = str(item).strip('[ ]')
fb.write(item+'\n')

点赞 打赏 评论