ex 3.3
This commit is contained in:
parent
830bca82c4
commit
0e72736371
19
reader.py
19
reader.py
@ -37,8 +37,8 @@ def read_csv_as_dicts(filename, conversions):
|
||||
headers = next(rows)
|
||||
for row in rows:
|
||||
value.append(
|
||||
{name: func(val)
|
||||
for name, func, val in zip(headers, conversions, row)})
|
||||
{name: func(val) for name, func, val in zip(headers, conversions, row)}
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
@ -49,6 +49,17 @@ def read_csv_as_columns(filename, conversions):
|
||||
value = DataCollection(headers)
|
||||
for row in rows:
|
||||
value.append(
|
||||
{name: func(val)
|
||||
for name, func, val in zip(headers, conversions, row)})
|
||||
{name: func(val) for name, func, val in zip(headers, conversions, row)}
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def read_csv_as_instances(filename, cls):
|
||||
"""Read a CSV file into a list of instances"""
|
||||
records = []
|
||||
with open(filename) as f:
|
||||
rows = csv.reader(f)
|
||||
_ = next(rows)
|
||||
for row in rows:
|
||||
records.append(cls.from_row(row))
|
||||
return records
|
||||
|
||||
16
stock.py
16
stock.py
@ -1,12 +1,21 @@
|
||||
import csv
|
||||
|
||||
from Decimal import Decimal
|
||||
|
||||
|
||||
class Stock:
|
||||
types = (str, int, float)
|
||||
|
||||
def __init__(self, name, shares, price):
|
||||
self.name = name
|
||||
self.shares = shares
|
||||
self.price = price
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, row):
|
||||
values = [func(val) for func, val in zip(cls.types, row)]
|
||||
return cls(*values)
|
||||
|
||||
def cost(self):
|
||||
return self.shares * self.price
|
||||
|
||||
@ -16,13 +25,6 @@ class Stock:
|
||||
self.shares = 0
|
||||
|
||||
|
||||
def read_portfolio(filename):
|
||||
with open(filename) as f:
|
||||
rows = csv.reader(f)
|
||||
_ = next(rows)
|
||||
return [Stock(row[0], row[1], row[2]) for row in rows]
|
||||
|
||||
|
||||
def print_portfolio(portfolio):
|
||||
headers = ("name", "shares", "price")
|
||||
fmtstr = "{0: >10} {1: >10} {2: >10}"
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user