[英]Iteration over a list of dictionaries
我正在尝试编写一个脚本,该脚本从两个.csv文件接收两个字典列表作为输入,检查键匹配,并给出另一个字典列表以及两个列表的输出。 到目前为止,我有:
import csv
def tabel_animals_func(file_csv):
with open(ficheiro_csv, 'rU') as file_csv_animals:
inputFile = csv.DictReader(file_csv_animals, delimiter=';')
result_animals = []
for line in inputFile:
result_animals.append(line)
return result_animals
def tabel_owners_func(file_csv2):
with open(file_csv2, 'rU') as file_csv_owners:
reader = csv.DictReader(file_csv_owners, delimiter=';')
result_owners = []
for line in reader:
result_owners.append(line)
return result_owners
def average_Age(tabela_animais, tabela_donos):
var_owners = tabel_owners_func(tabel_owners)
var_animals = tabel_animals_func(tabel_animals)
我需要输出第三个函数,一个新的拥有所有者动物平均年龄的字典列表,输出是这样的:
[{'Owners Name' : 'Jack', 'Average age' : '5'}, {'Owners Name' : 'Tom', 'Average age' : '8'}]
这是tabel_animals_func的输入.csv文件示例:
Name of the animal;Species;Age
Kiko;Cat;8
Rocky;Turtle;57
Snoopy;Dog;12
Nemo;Fish;2
Leonardo;Turtle;45
Milo;Dog;9
Raphael;Turtle;57
Dory;Fish;4
tabel_owners_func输入文件:
Owners Name;Name of the animal
Ana;Michelangelo
Tom;Dory
Jack;Kiko
Tom;Snoopy
Eva;Rocky
Sara;Raphael
Jack;Nemo
首先,我建议您合并两个CSV读取功能。 如果退后一步,您会发现这些功能实际上只是在做同样的事情。 将它们组合成read_csv_contents
函数或其他内容。
您可能应该将动物阅读器返回的字典列表转换为以动物名称为键的字典:
var_animals = tabel_animals_func(tabel_animals)
animals = {data['Name of animal']:data for data in var_animals}
一旦有了它们,就可以找到每个所有者拥有的动物列表:
pets = {}
for owner in var_owners:
o_name = owner['Owners Name']
if o_name not in pets:
pets[o_name] = []
pets[o_name].append(animals['Name of animal'])
通过列出每个人的宠物清单,可以轻松进行数学计算:
for owner,pet_list in pets.items():
npets = len(pet_list)
avg_age = sum([pet['Age'] for pet in pet_list]) / npets
奥斯汀的建议回答了单独的csv文件阅读器,我将其替换为一个函数,并将其read_csv
。 average_age函数做了很多工作。 如果有您不懂的地方,请告诉我来解释。
我认为这是您的解决方案(我的英语不好,所以我没有深入解释);
import csv
def read_csv(filename):
with open(filename, 'r') as file:
input_file = csv.DictReader(file, delimiter=";")
results = []
for line in input_file:
results.append(line)
return results
def get_age(animal_name):
# the function calculate the age of given animal
for a in animal_age:
if a['Name of the animal'] == animal_name:
return int(a['Age'])
def average_age(owners_animal):
# the function return a list which contain all owners and its animals' average age
results = []
owners_list = []
animal_list = []
for o in owners_animal:
if o['Owners Name'] not in owners_list:
owners_list.append(o['Owners Name'])
result = {'Owners Name': o['Owners Name'], 'Ages': []}
age = get_age(o['Name of the animal']) or 0
result['Ages'].append(age)
results.append(result)
else:
for r in results:
if r['Owners Name'] == o['Owners Name']:
r['Ages'].append(get_age(o['Name of the animal']))
results = [{'Owners Name': obj.get('Owners Name'), 'Average age': int(sum(obj['Ages'])/len(obj['Ages']))} for obj in results]
print(results)
owners_animal = read_csv("tabel_owners.csv") # the owner table
animal_age = read_csv("tabel_animals.csv") # the animal table
average_age(owners_animal)
Ana
的动物的价值不正确, Michelangelo
没有出现在Age
表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.