【发布时间】:2020-08-31 03:43:14
【问题描述】:
我必须创建一个名为 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])
【问题讨论】:
-
您的
read_data不是return任何东西,只是打印。所以readings = read_data(FILENAME)是None -
我应该怎么做才能让它返回字典
-
正如@Chris 所说,将
print(readings)更改为return readings。 -
或者添加
return readings作为每个函数的最后一行,以防您希望它们同时打印和返回。不要忘记更改get_average_dictionary;) -
实际上,我不认为这就是全部。我在下面提到了另外两个部分。
标签: python python-3.x dictionary dictionary-comprehension