gpt4 book ai didi

python - 如何在Python中打印字典键值的平均值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:30 25 4
gpt4 key购买 nike

Python 问题:

我一直在尝试让 Python 3 打印我的字典的平均值、sum/len。

我一直在研究如何在堆栈溢出中查找字典中值的平均值的方法,但每次我尝试使用字典中值的键来执行此操作时,我都会遇到错误。我能够让 len 工作,但除以它不起作用。

*TL:DR 如何打印字典中值的平均值?在注释行上。

我已经清理了我的代码并留下了一个空行来放入正确的代码。

import operator
"Dictionary"
time = {
'Kristian':19,
'Alistair':27,
'Chris':900,
'Maxi':50,
'Jack':15,
'Milk Man':1
}
print(time)
print ("-------------------------------")
"Printing the List"
for xyz in time:
print ("-------------------------------")
print("\nStudent Name: ", xyz,"\n Time: ", time[xyz],"seconds\n")

"Printing the Results"
def results():
print ("-------------------------------")
print("\nThe Fastest Time is: ",(time[min(time, key=time.get)]),"seconds")
print("\nThe Slowest Time is: ",(time[max(time, key=time.get)]),"seconds")
print("\nNo. of Competitors: ",len(time))
"//////////Here is where I want to print the mean score\\\\\\\\\\"

results()

"Adding to the Results"
def question():
person = input("\nPlease enter the student's name: ")
secs = int(input("Please enter the student's time in seconds: "))
print("The results you have added are:")
print("\nStudent Name: ", person,"\n Time: ", secs,"seconds\n")
sure = input("Are you sure? ").lower()
if sure in ("no", "n", "nope"):
question()
else:
time.update({person:secs})
print("Student has been added successfully.")
results()

"Running the loop"
question()

最佳答案

你指的是字典的,而不是,对吧?那么这将起作用(使用 statistics.mean ):

from statistics import mean
time = {
'K':19,
'Al':27,
'Chris':900,
'Max':50,
'Jack':15,
'Milk Man':1
}

print(mean(time.values())) # 168.66666666666666

使用dict.values您还可以轻松获得更简单的最大值:

print(max(dct.values()))

也许时间不是字典的最佳名称;标准库中有一个名为time的模块。如果您将其导入到同一个文件中,您将覆盖该模块。

关于python - 如何在Python中打印字典键值的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41790580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com