我试着用这一大块代码做3个独立的函数。一种是计算字典中键的字母顺序,一种是计算字典中值的最高分数,另一种是从字典中找出平均分数
以下是三本词典:
class_1={"Mike":[2,3,2,5,3],"Jack":[1,2,1,6,4],"Rob":[0,2,6,4]}
class_2={"Steve":[2,5,2,5,9],"Mo":[3,2,1,6,4],"Bill":[9,2,6,4]}
class_3={"Harry":[1,3,1,5,3],"Dave":[7,2,1,6,4],"Molly":[3,2,9,4]}
使用这一大块代码,我可以做我想实现的事情,但它看起来并不优雅或高效。你知道吗
class_choice_menu=input("Please choose the class you would like to check:\n\
1.Class 1\n\
2.Class 2\n\
3.Class 3\n")
class_choice=int(class_choice_menu)
if class_choice ==1:
class_1_average = {key: int(sum(value)/len(value)) for key, value in class_1.items()}
max_each_1 = {key: max(value) for key, value in class_1.items()}
print("Alphabetically")
for key in sorted(max_each_1.keys()):
print ("%s: %s" % (key, max_each_1[key]))
print ('\nSort by average scores(descending order):')
for key, value in sorted(class_1_average.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, class_1_average[key]))
print ('\nSort by high scores(descending order):')
for key, value in sorted(max_each_1.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, max_each_1[key]))
elif class_choice ==2:
class_2_average = {key: int(sum(value)/len(value)) for key, value in class_2.items()}
max_each_2 = {key: max(value) for key, value in class_2.items()}
print("Alphabetically")
for key in sorted(max_each_2.keys()):
print ("%s: %s" % (key, max_each_2[key]))
print ('\nSort by average scores(descending order):')
for key, value in sorted(class_2_average.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, class_2_average[key]))
print ('\nSort by high scores(descending order):')
for key, value in sorted(max_each_2.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, max_each_2[key]))
elif class_choice ==3:
class_3_average = {key: int(sum(value)/len(value)) for key, value in class_3.items()}
max_each_3 = {key: max(value) for key, value in class_3.items()}
print("Alphabetically")
for key in sorted(max_each_3.keys()):
print ("%s: %s" % (key, max_each_3[key]))
print ('\nSort by average scores(descending order):')
for key, value in sorted(class_3_average.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, class_3_average[key]))
print ('\nSort by high scores(descending order):')
for key, value in sorted(max_each_3.items(), reverse = True, key=lambda item: (item[1], item[0])):
print ("%s: %s" % (key, max_each_3[key]))
我试过一次,但似乎不管用
def alphabetical(class_choice):
max_each_%s= {key:max(value) for key,value in class_%s.items()}
print("Alphabetically")
for key in sorted (max_each_%s.keys()):
print("%s: %s" % (key,max_each_%s[key] % class_choice))
我知道你需要什么。你知道吗
首先,您需要了解如何定义函数。你知道吗
让我们看看你的代码。你知道吗
我建议你要扩展类变量,很容易维护。它可以基于用户输入和if-else语句返回您选择的值。你知道吗
为了简化你的代码。我们可以重用这些代码。你知道吗
当您想处理数据时,只需使用这些函数。它也可以这样做。你知道吗
相关问题 更多 >
编程相关推荐