读取文本文件并排序输出python_将文本文件中的值从最高到最低排序为python

也许是这样吧from __future__ import division

from operator import attrgetter

class Player(object):

def __init__(self, name, scores):

self.name = name

self.scores = scores

self.highscore = max(scores)

self.avgscore = sum(scores) / len(scores)

with open('scorez.txt') as f:

players = []

for line in f:

elems = line.split(',')

players.append(Player(elems[0], map(int, elems[1:])))

byhighscore = sorted(players, key=attrgetter('highscore'), reverse=True)

byavg = sorted(players, key=attrgetter('avgscore'), reverse=True)

print('')

for p in byhighscore:

print('{0} {1:g}'.format(p.name, p.highscore))

print('')

for p in byavg:

print('{0} {1:g}'.format(p.name, p.avgscore))

将文件读入玩家列表,并预先计算最大得分和平均得分(如果玩家和/或得分列表较大,则此操作可能会推迟)。然后只需对所需的属性进行排序并打印即可。在

对于初学者来说,attrgetter函数可能有点奇怪,但它基本上只返回列表中被排序的每个元素的给定属性。在

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页