如何在阵列中存储程序的多个结果?
对于我的数组中的每个人,我需要存储3个结果,但每次执行此操作时,程序运行时都会出错。
我无法在程序运行时找到3个数组中每个人的平均分数。
我是PYTHON的新人。
import operator
print("if form1 enter x, if form2 enter y,if form 3 enter z")
print("to view all results enter allscore")
x={"guv":1,"jane":4,"adam":5,"luiz":8,"elizabeth":9,"paul":10,"guv":3}
sorted(x.items(), key=operator.itemgetter(1), reverse=True) #sorts x from high to low
sorted(x.items()) #sorts x alphabetically
y={"adrian":0,"anna":9,"david":7,"matt":10,"micheal":5}
sorted(y.items(), key=operator.itemgetter(1), reverse=True)
sorted(y.items())
z={"gus":6,"mohammed":6,"winston":9,"barry":9,"ping":3}
sorted(z.items(), key=operator.itemgetter(1), reverse=True)
sorted(z.items()) #
allscore={}
allscore.update(x) # to get data from array x
allscore.update(y) # to get data from array y
allscore.update(z) # to get data from array z
#stores all data in this array
答案 0 :(得分:0)
如果要为每个用户存储多个值,可以使用tuples。
scores = {
"guv": (1, 2, 3),
"jane": (4, 5, 6),
"luiz": (7, 8, 9),
}
然后,您可以使用以下循环获取所有用户的平均值:
for name in scores:
average = sum(scores[name]) / len(scores[name])
print("Average for " + name + ": " + str(average))
如果您希望能够添加分数,请改用lists。
按字母顺序打印分数:
for name in sorted(scores):
print("Scores for " + name + ": " + str(scores[name]))
用于打印从最高平均值到最低平均值的分数:
averages = {
name: sum(scores[name]) / len(scores[name])
for name in scores.keys()
}
for name in sorted(averages, key=averages.get, reverse=True):
print("Average score for " + name + ": " + str(averages[name]))