[英]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.