我正在尝试将从文件中提取的一些数据按字母顺序排序(工作)对数据进行平均(添加所有数据,忽略字母,并对所有数据进行平均),最后将分数从最高到最低排序(再次将用户名放在第一位,但也尚未完成)。请帮忙,这是他的代码:
(wf被设置为要查看文件的内容)
sort = input("What would you like to do with this class? Put them into alpabetical order(a)? Average the scores(b)? Highest to lowest(c)?")
with open(wf, 'r') as r:
if sort == 'a':
for line in sorted(r):
print(line, end = '')
elif sort == 'b':
for line in sorted(r):
print()
elif sort == 'c':
def score(line):
return int(line.split(',')[1])
with open(wf, 'r') as r:
list.sort(r)
for line in sorted(r,reverse=True):
print(line)
求平均值:
要得到平均值,你需要把所有的分数加在一起,然后除以分数。你可以通过迭代行并将所有分数相加,然后除以的行数来实现这一点
按分数排序:
您需要调用sorted()函数并提供自己的密钥。你有一个功能几乎做到了,我只是稍微修复了一下。你将行列表和返回分数的键发送给它,然后将其反转,因为你希望它们从最高到最低。然后只需要循环浏览新的排序列表并打印每行
总体意见
这个程序的结构非常混乱和多余。你应该先把文件读一遍,然后把所有的东西都弄清楚。在每个if语句中遍历文件的速度很慢。您还应该使用函数来实现这一点。制作一个返回平均值的函数,一个返回按分数排序的列表的函数等。让代码全部乱序只会让很难读取
我已经在下面的代码中实现了这些,但我建议你自己尝试一下,因为你已经知道该怎么做了,并且只有在你遇到时才使用这个代码作为参考
sort = input("What would you like to do with this class? Put them into alpabetical order(a)? Average the scores(b)? Highest to lowest(c)?")
wf = "file.txt"
with open(wf, 'r') as r:
if sort == 'a':
for line in sorted(r):
print(line, end = '')
elif sort == 'b':
totalScore = 0
numOfScores = 0
for line in sorted(r):
numOfScores += 1
totalScore+= int(line.split('score = ')[1])
average = totalScore / numOfScores
print(average)
elif sort == 'c':
def score(line):
return int(line.split('=')[1])
with open(wf, 'r') as r:
linesList = r.readlines()
sortedList = sorted(linesList, key=score)
for line in sortedList:
print(line.rstrip("n"))
对于这个例子,我使用了你提供的例子分数文件,比如:
bob - score = 12
harry - score = 1
ellis - score = 21
sam - score = 30