Commit ca359d05 by Patryk Czarnik

wersja namedtuple

parent a4e159e6
from collections import namedtuple
nazwy_kolumn = ('employee_id', 'first_name', 'last_name', 'job_title', 'salary', 'hire_date',
'department_name', 'address', 'postal_code', 'city', 'country')
Employee = namedtuple('Employee', nazwy_kolumn)
def read_csv(path):
emps = []
with open(path, mode='r', encoding='utf-8') as file:
file.readline()
for line in file:
t = line.strip().split(';')
emp = Employee(int(t[0]), t[1], t[2], t[3], int(t[4]), *t[5:])
emps.append(emp)
return emps
from employees import read_csv
emps = read_csv('emps.csv')
print('Liczba odczytanych rekordów:', len(emps))
for emp in emps:
print(emp)
from employees import read_csv
emps = read_csv('emps.csv')
for emp in emps:
print(f'Pracownik {emp.first_name} {emp.last_name} ({emp.job_title}) zarabia ${emp.salary}')
# print(f'Pracownik {emp[1]} {emp[2]} ({emp[3]}) zarabia {emp[4]} USD')
# Dla obiektów namedtuple możliwy jest dostęp dol pól poprzez nazwę atrybutu oraz przez numer pozycji
from collections import defaultdict
from employees import read_csv
emps = read_csv('emps.csv')
# Jako parametr defaultdict wpisuje się "przepis na nowy element".
# Gdy podajemy przykładowo int, to używane jest to w taki sposób, że jest wywoływane int() , a to daje wynik 0.
# Tutaj podamy funkcję, która nie pobiera argumentów, a wyniku zwraca nową listę zaweirającą dwa zera.
slownik = defaultdict(lambda: [0, 0])
for emp in emps:
slownik[emp.job_title][0] += 1
slownik[emp.job_title][1] += emp.salary
print(slownik)
print()
for job, (ilosc, suma) in slownik.items():
srednia = suma / ilosc
print(f'| {job:32} | {ilosc:2} | {srednia:8.2f} |')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment