帮助使用哪些功能
如何实现这一目标:
最终产品应该是:
Highest scores in descending order:
Name1 , HiScore1
Name2 , HiScore2
Name3 , HiScore3
Highest average scores in descending order:
Name1 , AvgScore1
Name2 , AvgScore2
Name3 , AvgScore3
Alphabetical order:
Name1 , AllScores
Name2 , AllScores
Name3 , AllScores
答案 0 :(得分:0)
希望这会有所帮助
import operator
class extractData:
def __init__(self):
self.student_higest_marks = {}
def get_content(self, filename):
f = open(filename, 'r')
data = f.read()
f.close()
return data
def get_name_marks(self, content):
for data in content.split('\n'):
name = data.split('=')[0]
marks = data.split('=')[1].strip()
if name in self.student_higest_marks:
self.student_higest_marks[name].append(int(marks))
else:
self.student_higest_marks[name] = [int(marks)]
return self.student_higest_marks
def cal_highest_marks(self):
print "Highest scores in descending order:"
highest_marks = dict((name, max(marks)) for name,marks in
self.student_higest_marks.items())
return sorted(highest_marks.items(), key=operator.itemgetter(1), reverse=True)
def alph_order(self):
print "Alphabetical order:"
return sorted(self.student_higest_marks.items(), key=operator.itemgetter(0))
def cal_avg_score(self):
print "Highest average scores in descending order:"
avg_marks = dict((name, reduce(lambda x,y:x+y,marks)/len(marks)) for name,marks in self.student_higest_marks.items())
return sorted(avg_marks.items() ,key=operator.itemgetter(1), reverse=True)
calObject = extractData()
content = calObject.get_content('Test Scores Class1.txt')
calObject.get_name_marks(content)
content = calObject.get_content('Test Scores Class2.txt')
calObject.get_name_marks(content)
print calObject.alph_order()
print calObject.cal_highest_marks()
print calObject.cal_avg_score()
希望你可以循环结果。