Код ниже:
Код: Выделить всё
from pprint import pprint
text = '''osis,exam1,exam2,exam3,exam4
123,95,100,97,93
207,95,75,88,90
307,60,76,68,75
736,80,a,58,99
380,64,64,90,87
347,61,58,63,65
806,58,68,57,70
943,60,62,100,99
986,65,59,55,84
784,87,63,66,74
846,91,76,65,56
520,a,95,62,67
222,66,a,57,72
313,74,64,99,a
621,61,79,57,85
658,56,79,60,66
597,68,56,88,76
775,a,59,87,65
308,75,78,61,68
897,66,60,56,98
501,58,68,67,80
509,56,91,90,74
269,75,a,a,66
913,74,70,90,63
748,68,67,90,59
798,a,61,78,82
573,74,69,70,84
985,a,99,89,62
338,a,64,99,87
605,86,61,100,90
262,68,a,100,86
582,85,74,71,a'''
print(text)
def two_d_list_maker(s):
return [item.split(',') for item in (text.split('\n')[:-1])]
data = two_d_list_maker(text)
pprint(data)
# Should print:
# [['osis', 'exam1', 'exam2', 'exam3', 'exam4']
# ['123', '95', '100', '97', '93']
# ['207', '95', '75', '88', '90']
# ...
# ]
def dict_maker(data):
return {sublist[0]:sublist[1:] for sublist in data[1:]}
grade_dict = dict_maker(data)
# Should print:
# {'123': ['95', '100', '97', '93'],
# '207': ['95', '75', '88', '90']
# ...
# }
pprint(grade_dict) # this prints a normal dictionary w/ numbers as strings
def avg_dict_maker(d):
for key in d.keys():
available_scores = [int(score) for score in d[key] if score != 'a']
d[key] = sum(available_scores)/len(available_scores)
if d[key] == int(d[key]):
d[key] = int(d[key])
return d
pprint(grade_dict) #still works fine
avg_dict = avg_dict_maker(grade_dict)
pprint(avg_dict) # this should be the only integer/floating number dictionary here
# Should print:
# {'123': 96.25,
# '207': 87,
# ...
# }
pprint(grade_dict) #this variable now prints the same thing as avg_dict
Подробнее здесь: https://stackoverflow.com/questions/784 ... to-another