我的代码如下,但是向我显示一条错误消息
ValueError: invalid literal for int() with base 10: '4\njohn'"
就行了
players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
代码:
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) / 3
with open('classFilea.txt') as f:
for l in f:
l = l.strip(); # Remove the end of line char (\n)
text = f.read()
players = []
elems = text.split(',')
for e in range(0,len(elems),4):
players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
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))
我的代码应该对数据进行排序,如:
Ahmed,1,6,4
John,5,3,5
Kali,5,4,7
Larry,4,7,6
按最高分和平均分
编辑代码:
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) / 3
with open('classFilea.txt') as f:
for l in f:
l = l.strip(); # Remove the end of line char (\n)
text = f.read()
players = []
elems = text.split(',')
for e in range(0,len(elems),4):
players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
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))
现在代码告诉我分数是空的。 我在一个单独的页面打印得分并打印“[]”我被告知这是由于我的代码逻辑。 “for f in f loop。之后,当前文件指针位于文件的末尾,因此下面的f.read()将不会获得任何数据。正如PM2Ring所说:”你需要重新组织代码的逻辑“
答案 0 :(得分:1)
当您添加包含要分数的字符串的列表时:
players.append(Player(elems[0], map(int, elems[1:])))
,并试图获得最大值:
self.highscore = max(scores)
您获得了您提到的错误。在您的代码中的这一点:
for line in f:
elems = line.split(',')
players.append(Player(elems[0], map(int, elems[1:])))
你需要确保“elems [1:]”不带字符串。这是您文件中的解析问题。如果每个人总是有4个元素(名称和3个数字),只需在构建一行时给出该指令:
for i in range(len(elems)//4):
players.append(Player(elems[4*i], map(int, elems[4*i+1:4*(i+1)])))
另外我建议你删除“地图”,因为它没有“len”,或者只是替换替换:
self.avgscore = sum(scores) / len(scores)
由:
self.avgscore = sum(scores) / 3
如果分数的长度始终为3。
答案 1 :(得分:1)
如果您的文本文件只包含一行,则需要相应地处理它。假设每个名称之间有三个值(编辑以考虑文件中实际上有多行):
with open('classFilea.txt') as f:
players = []
for line in f:
elems = line.split(',')
for e in range(0,len(elems),4):
players.append(Player(elems[e], list(map(int, elems[e+1:e+4]))))
这里e
遍历elems的每四个索引。
此方法的替代方法是更改输入文件的制作方式,以便每行只有一个Player
数据。
此外,您的Type Error
可能是由于您使用Python 3,其中map
出于性能原因生成迭代器。这可以通过将其重新设置为list
来解决。