【发布时间】:2016-04-28 18:17:56
【问题描述】:
我必须创建一个接受两个参数(.csv 文件的名称)的函数,在该函数中计算某个人的宠物的平均年龄。
我的函数需要读取这个 .csv 文件并返回另一个 .csv 文件,其中包含宠物的平均年龄,由主人的年龄区分。例如,John 有三只宠物(Michalengelo、Leonardo 和 Raphael),因此函数会读取两个 .csv 文件并计算 John 宠物年龄的平均值。亚当和伊娃也是如此。
我有一个函数可以获取 csv 文件并将其转换为字典。例如(使用第一个 csv 文件):
read_csv_to_dict('Pets_info.csv'):
>>> [{'Age': '8', 'Name of the Pet': 'Felix', 'Species': 'Cat'}, {'Age': '57', 'Name of the Pet': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': '12', 'Name of the Pet': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Name of the Pet': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Name of the Pet': 'Leonardo', 'Species': 'Tortoise'}, {'Age': '9', 'Name of the Pet': 'Milo', 'Species': 'Dog'}, {'Age': '57', 'Name of the Pet': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Name of the Pet': 'Dory', 'Species': 'Fish'}]
我想如果我用字典处理这些数据,我可以得到我想要的,我只是不知道该怎么做。 如果您不理解我的,请随时提出任何问题。 提前致谢。
【问题讨论】:
标签: python python-2.7 csv dictionary