简体   繁体   English

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

[英]How can I print the mean of key values of a dictionary in Python?

Python Question:蟒蛇问题:

I've been trying to get Python 3 to print the mean, sum/len of my dictionary.我一直在尝试让 Python 3 打印字典的平均值、总和/长度。

I've been looking at methods on stack overflow of how to find the mean of values in a dictionary but every time I try to do it using the keys of values in a dictionary I am riddled with errors.我一直在研究如何在字典中找到值的平均值的堆栈溢出方法,但是每次我尝试使用字典中的值的键来做它时,我都会遇到错误。 I was able to get the len to work but dividing it doesn't work.我能够让 len 工作,但分割它不起作用。

*TL:DR How do I print the mean of values from a Dictionary? *TL:DR如何打印字典中值的平均值? on the commented line.在注释行上。

I have cleaned out my code and left an empty line to put in the correct code.我已经清理了我的代码并留下了一个空行来输入正确的代码。

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()

you mean the values of the dictionary, not the keys , right?你的意思是字典的,而不是,对吗? then this would work (using statistics.mean ):那么这将起作用(使用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

using dict.values you could also easily get the maximal value a little simpler:使用dict.values您还可以轻松获得更简单的最大值:

print(max(dct.values()))

maybe time is not the best name for the dictionary;也许time不是字典的最佳名称; there is a module in the standard library called time .标准库中有一个名为time的模块。 you'd overwrite this module should you import it in the same file.如果您将它导入到同一文件中,您将覆盖此模块。

dict.values() returns the list of all the values in the Python dictionary. dict.values()返回 Python 字典中所有值的列表 In order to calculate the mean, you may do:为了计算平均值,您可以执行以下操作:

>>> time_values = list(time.values())
#                  ^  Type-cast it to list. In order to make it
#                     compatible with Python 3.x    

>>> mean = sum(time_values)/float(len(time_values))
#                             ^ in order to return the result in float.
#                               division on two `int` returns int value in Python 2    

The value hold by mean will be: mean持有的价值将是:

>>> mean
168.66666666666666

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 Python 字典打印为按键深度排序的 YAML - How can I print a Python dictionary as YAML sorted by key depth 如何在 Python 的 GUI 中打印字典中的所有值 - How can i print all values from a dictionary in a GUI in Python 我想在 python 中将 output 打印为 1 键 2 值对(字典) - I want to print output as 1 key 2 values pairs(dictionary) in python 我有一个txt文件。 如何获取字典键值并打印出现在其中的文本行? - I have a txt file. How can I take dictionary key values and print the line of text they appear in? 如何仅打印嵌套字典 [Python] 中特定键的值的总和? - How can you print the sum of only the values of specific key in a nested dictionary [Python]? 在python词典中,如果存储了多个值,如何打印键的值? - In dictionary of python how to print value of a key if it have multiple values stored? Python,如何在每一行中打印字典键及其值? - Python, how to print dictionary key and its values in each line? 如何在Python中的字典中打印列表? - How can I print list in dictionary in Python? Python tkinter combobox select 字典键如何打印对应值? - Python tkinter combobox, how can I select dictionary key and print corresponding value? 如何在 Python 的字典中打印给定值的键? - How can you print a key given a value in a dictionary for Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM