在上一个练习中,我编写了一个代码,打印了csv文件中每个山峰的高度。您可以在这里找到它:
import csv
def mountain_height(filename):
""" Read in a csv file of mountain names and heights.
Parse the lines and print the names and heights.
Return the data as a dictionary.
The key is the mountain and the height is the value.
"""
mountains = dict()
msg = "The height of {} is {} meters."
err_msg = "Error: File doesn't exist or is unreadable."
# TYPE YOUR CODE HERE.
try:
with open('mountains.csv','r') as handle:
reader = csv.reader(handle,delimiter=',')
for row in reader:
name = row[0]
height = row[1]
mountains[name] = int(height)
for name,height in mountains.items():
print("The height of {names} is {heights} meters.".format(names=name,heights=height))
except:
print("Error: Something wrong with your file location?")
return None
我不确定它是否理想,但似乎可行。
这是csv文件的预览: mountains.csv
现在,我必须使用集合的模块Counter重写此代码,以计算提到每个山脉的次数。每行都包含一座山,其高度及其一部分。
我还需要添加一个字典,以记录特定范围内所有山脉的高度。我必须使用一个列表作为高度值。关键将是范围名称。每次在该范围内有一座新山峰时,都必须将高度添加到该钥匙的列表中。例如,在读取所有数据之后,mountain ['Himalayas'] == [8848、8586、8516、8485、8201、8167、8163、8126、8091、8027]。 (“喜马拉雅山”就是范围。)
输出应该是打印前两个范围并将范围名称添加到计数器。 然后,打印每个范围内山脉的平均高度。完成所有打印后,返回字典对象及其范围和山高列表。
我对Counter模块的了解很小,我对这项任务感到不知所措。 您对从哪里开始有什么建议?
这是到目前为止我得到的:
from collections import Counter
from collections import defaultdict
from statistics import mean
def mountain_ranges(filename):
ranges = Counter()
heights = defaultdict(list)
提前谢谢您。...