获取字典列表中值的平均值

时间:2020-08-31 03:43:14

标签: python python-3.x dictionary dictionary-comprehension

我必须创建一个名为read_data的函数,该函数将文件名作为其唯一参数。然后,此函数必须使用给定名称打开文件并返回字典,其中的键是文件中的位置名称,值是读数列表。

第一个函数的结果有效并显示:

{'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], ‘Thursday’:[15, 35],’Friday’:[70, 31],’Saturday’;[34, 39],’Sunday’:[22, 18]}

第二个名为get_average_dictionary的函数,该函数将结构如read_data的返回值的字典作为其唯一参数,并返回具有与该参数相同的键,但具有读数平均值而不是各个读数列表的字典。这必须返回:

{'Monday': [55.00], 'Tuesday': [20.00], 'Wednesday': [56.00], ‘Thursday’:[25.00],’Friday’:[50.50],’Saturday’;[36.50],’Sunday’:[20.00]}

但是我无法使其正常工作。我收到以下错误:

line 25, in <module>
    averages = get_average_dictionary(readings)
line 15, in get_average_dictionary
    average = {key: sum(val)/len(val) for key, val in readings.items()}
AttributeError: 'NoneType' object has no attribute 'items'

这是我目前的代码。任何帮助将不胜感激。

def read_data(filename):
    readings = {}

    with open("c:\\users\\jstew\\documents\\readings.txt") as f:
        for line in f:
            (key, val) = line.split(',')
            if not key in readings.keys():
                readings[key] = []

            readings[key].append(int(val))

    print(readings)

def get_average_dictionary(readings):
    average = {key: sum(val)/len(val) for key, val in readings.items()}

    print(average)


FILENAME = "readings.txt"

if __name__ == "__main__":
    try:
        readings = read_data(FILENAME)
        averages = get_average_dictionary(readings)


        # Loops through the keys in averages, sorted from that with the largest associated value in averages to the lowest - see https://docs.python.org/3.5/library/functions.html#sorted for details
        for days in sorted(averages, key = averages.get, reverse = True):
            print(days, averages[days])

2 个答案:

答案 0 :(得分:2)

给出:

di={'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], 'Thursday':[15, 35],'Friday':[70, 31],'Saturday':[34, 39],'Sunday':[22, 18]}

您可以这样做:

>>> {k:sum(v)/len(v) for k,v in di.items()}
{'Monday': 55.0, 'Tuesday': 20.0, 'Wednesday': 56.0, 'Thursday': 25.0, 'Friday': 50.5, 'Saturday': 36.5, 'Sunday': 20.0}

您似乎遇到的错误是您没有从函数中返回任何内容。只要做:

def a_func(di):
    return {k:sum(v)/len(v) for k,v in di.items()}

你应该很好...

答案 1 :(得分:0)

您很亲近,但至少有一个问题。一个是这个:

Friday’:[50.50],’Saturday’;[36.50],’Sunday’: [22, 18]

请注意,“星期六”后接分号,而不是冒号。在两个示例中都是这样。此外,请注意您的文本颜色从红色变为蓝色。通常(包括这种情况)意味着您从单引号切换到了智能引号或看起来像普通引号但无法识别的字符。

{'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], ‘Thursday’:[15, 35],’Friday’:[70, 31],’Saturday’;[34, 39],’Sunday’:[22, 18]}

一旦清除了这些内容,您只需要处理最后一部分,就可以返回打印结果。

def get_average_dictionary(readings):
    return {k:(sum(v)/len(v)) for (k,v) in vals.items()}