parse_csv which will load tables from file and return a 2D list as given below
%%file tables.csv
1,2,3,4,5
2,4,6,8,10
3,6,9,12,15
4,8,12,16,20
5,10,15,20,25
6,12,18,24,30
7,14,21,28,35
8,16,24,32,40
9,18,27,36,45
10,20,30,40,50
if tables.csv contains above data, the function should work as given below
>>> parse_csv("tables.csv")
[[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
[4, 8, 12, 16, 20],
[5, 10, 15, 20, 25],
[6, 12, 18, 24, 30],
[7, 14, 21, 28, 35],
[8, 16, 24, 32, 40],
[9, 18, 27, 36, 45],
[10, 20, 30, 40, 50]]
+----------------------------+
| |
| student_names |--------->get_score(name)
names--->| scores_for_assignment |
| |--------->assign_score(name, score)
| |
| |--------->get_average_score()
| |
+-----------------------------
text = "[1, 2, 3, 4, 5]"
%%file tables.csv
1,2,3,4,5
2,4,6,8,10
3,6,9,12,15
4,8,12,16,20
5,10,15,20,25
6,12,18,24,30
7,14,21,28,35
8,16,24,32,40
9,18,27,36,45
10,20,30,40,50
Overwriting tables.csv
row = "1,2,3,4,5"
row.split(",")
['1', '2', '3', '4', '5']
[int(item) for item in row.split(",")]
[1, 2, 3, 4, 5]
def parse_csv(filename):
with open(filename) as f:
data = []
for line in f:
rowdata = [int(item) for item in line.split(",")]
data.append(rowdata)
return data
parse_csv("tables.csv")
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25], [6, 12, 18, 24, 30], [7, 14, 21, 28, 35], [8, 16, 24, 32, 40], [9, 18, 27, 36, 45], [10, 20, 30, 40, 50]]
def parse_csv(filename):
"""this will parse matrix of intengers from a file
"""
with open(filename) as f:
return [[int(item) for item in line.split(",")] for line in f]
parse_csv("tables.csv")
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25], [6, 12, 18, 24, 30], [7, 14, 21, 28, 35], [8, 16, 24, 32, 40], [9, 18, 27, 36, 45], [10, 20, 30, 40, 50]]
f = open("tables.csv")
help(f.read)
Help on built-in function read:
read(size=-1, /) method of _io.TextIOWrapper instance
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.
f.read(5) # read next 5 characters
'1,2,3'
f.read(10) # read next
',4,5\n2,4,6'
class PythonClassRoom:
def __init__(self, names):
self._scores = {}
names = ["A","B","C","D"]
scores = {}
for name in names:
scores[name] = -1
scores
{'A': -1, 'B': -1, 'C': -1, 'D': -1}
{name:-1 for name in names} # dictionary comprehansion
{'A': -1, 'B': -1, 'C': -1, 'D': -1}
[int(item) for item in row.split(",")]
[1, 2, 3, 4, 5]
[1,2,3]
{"a":1, "b":2, "c":3}
class PythonClassRoom:
def __init__(self, names):
self._scores = {name:-1 for name in names}
# we will store data as a dictionary
# initialized it with -1 scores for all the student
def get_score(self, name):
return self._scores[name]
def assign_score(self, name, score):
self._scores[name] = score
def get_average_score(self):
s = 0
count = 0
for name,score in self._scores.items():
if score >= 0:
s += score
count += 1
return s/count
def get_average_score(self):
solved_scores = [score for name, score in self._scores.items() if score>=0]
return sum(solved_scores)/len(solved_scores)
list("ABCDEF")
['A', 'B', 'C', 'D', 'E', 'F']
c = PythonClassRoom(list("ABCDEF")
c.get_score("A")
-1
c.assign_score("B", 80)
c.get_score("B")
80
c.get_average_score()
80.0
c.assign_score("C", 90)
c.get_average_score()
85.0
import csv
%%file data.csv
ticker,value,open,close,high,low
XEFD,123,124,125,127,120.0
RTRT,567,565,564,569,560.5
RTAT,567,565,564,569,560.4
RCRT,567,565,564,569,560.2
RTRT,567,565,564,569,560.1
Overwriting data.csv
parse_csv("data.csv") # our function does not handle column headers and also types of columns
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-45-dfaa2971ba09> in <module> ----> 1 parse_csv("data.csv") # our function does not handle column headers and also types of columns <ipython-input-18-2464182c2bc5> in parse_csv(filename) 3 """ 4 with open(filename) as f: ----> 5 return [[int(item) for item in line.split(",")] for line in f] 6 7 <ipython-input-18-2464182c2bc5> in <listcomp>(.0) 3 """ 4 with open(filename) as f: ----> 5 return [[int(item) for item in line.split(",")] for line in f] 6 7 <ipython-input-18-2464182c2bc5> in <listcomp>(.0) 3 """ 4 with open(filename) as f: ----> 5 return [[int(item) for item in line.split(",")] for line in f] 6 7 ValueError: invalid literal for int() with base 10: 'ticker'
import csv
def read_csv(filename):
with open(filename) as f:
csvreader = csv.reader(f) # csvreader is ierator but instaed giving line as a text it gives list of fileds
data = []
for row in csvreader:
data.append(row)
return data
f = open("data.csv")
csvreader = csv.reader(f)
csvreader # it is an iterator
<_csv.reader at 0x7f00ca604510>
next(csvreader)
['ticker', 'value', 'open', 'close', 'high', 'low']
next(csvreader)
['XEFD', '123', '124', '125', '127', '120.0']
def read_csv(filename):
with open(filename) as f:
csvreader = csv.reader(f) # csvreader is iterator but instaed giving line as a text it gives list of fileds
data = []
headers = next(csvreader) # read headers seperately
for row in csvreader:
data.append(row)
return headers, data
headers, data = read_csv("data.csv")
headers
['ticker', 'value', 'open', 'close', 'high', 'low']
data
[['XEFD', '123', '124', '125', '127', '120.0'], ['RTRT', '567', '565', '564', '569', '560.5'], ['RTAT', '567', '565', '564', '569', '560.4'], ['RCRT', '567', '565', '564', '569', '560.2'], ['RTRT', '567', '565', '564', '569', '560.1']]
file -> f (open) -> csvreader (csv.reader(f)
------------------ ---------- ----------------
++++++++++++++++ + + --> one line out
------------------ ---------- ----------------
items = [1, 2, 3, 4]
# for loop is working this logic
items_ = iter(items)
next(items_)
next(items_)
next(items_)
3
next(items_)
4
next(items_)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-22-9ef95e9998b4> in <module> ----> 1 next(items_) StopIteration:
def read_csv(filename):
with open(filename) as f:
csvreader = csv.reader(f) # csvreader is iterator but instaed giving line as a text it gives list of fileds
data = []
#headers = next(csvreader) # read headers seperately
for row in csvreader:
data.append(row)
return data
read_csv("data.csv")
[['ticker', 'value', 'open', 'close', 'high', 'low'], ['XEFD', '123', '124', '125', '127', '120.0'], ['RTRT', '567', '565', '564', '569', '560.5'], ['RTAT', '567', '565', '564', '569', '560.4'], ['RCRT', '567', '565', '564', '569', '560.2'], ['RTRT', '567', '565', '564', '569', '560.1']]
def read_csv(filename, fields):
with open(filename) as f:
csvreader = csv.reader(f) # csvreader is iterator but instaed giving line as a text it gives list of fileds
data = []
headers = next(csvreader) # read headers seperately
for row in csvreader:#iterator, so at a time one list comes
converted_row = [convert(item) for item, convert in zip(row, fields)]
data.append(converted_row)
return headers, data
read_csv("data.csv", [str, int, int, float, float, float])
(['ticker', 'value', 'open', 'close', 'high', 'low'], [['XEFD', 123, 124, 125.0, 127.0, 120.0], ['RTRT', 567, 565, 564.0, 569.0, 560.5], ['RTAT', 567, 565, 564.0, 569.0, 560.4], ['RCRT', 567, 565, 564.0, 569.0, 560.2], ['RTRT', 567, 565, 564.0, 569.0, 560.1]])
row = ['XEFD', '123', '124', '125', '127', '120.0']
fields = [str, int, int, float, float, float]
for item, convert in zip(row, fields):
print(convert(item))
XEFD 123 124 125.0 127.0 120.0
[convert(item) for item, convert in zip(row, fields)]
['XEFD', 123, 124, 125.0, 127.0, 120.0]
fields = [("value", float),
("open", float),
("close", float),
("high", float),
("low", float)
]
with open("data.csv") as f:
csvdict = csv.DictReader(f)
for row in csvdict:
print(row)
{'ticker': 'XEFD', 'value': '123', 'open': '124', 'close': '125', 'high': '127', 'low': '120.0'}
{'ticker': 'RTRT', 'value': '567', 'open': '565', 'close': '564', 'high': '569', 'low': '560.5'}
{'ticker': 'RTAT', 'value': '567', 'open': '565', 'close': '564', 'high': '569', 'low': '560.4'}
{'ticker': 'RCRT', 'value': '567', 'open': '565', 'close': '564', 'high': '569', 'low': '560.2'}
{'ticker': 'RTRT', 'value': '567', 'open': '565', 'close': '564', 'high': '569', 'low': '560.1'}
fields = [("value", float),
("open", float),
("high", float),
("low", float)
]
with open("data.csv") as f:
csvdict = csv.DictReader(f) # it makes used of column headers to create dictionary for evry row
for row in csvdict:
row.update((colname, convert(row[colname])) for colname, convert in fields)
print(row)
{'ticker': 'XEFD', 'value': 123.0, 'open': 124.0, 'close': '125', 'high': 127.0, 'low': 120.0}
{'ticker': 'RTRT', 'value': 567.0, 'open': 565.0, 'close': '564', 'high': 569.0, 'low': 560.5}
{'ticker': 'RTAT', 'value': 567.0, 'open': 565.0, 'close': '564', 'high': 569.0, 'low': 560.4}
{'ticker': 'RCRT', 'value': 567.0, 'open': 565.0, 'close': '564', 'high': 569.0, 'low': 560.2}
{'ticker': 'RTRT', 'value': 567.0, 'open': 565.0, 'close': '564', 'high': 569.0, 'low': 560.1}
def get_column(filename, name, type_):
with open(filename) as f:
return [type_(row[name]) for row in csv.DictReader(f)]
get_column("data.csv", "value", int)
[123, 567, 567, 567, 567]
get_column("data.csv", "low", float)
[120.0, 560.5, 560.4, 560.2, 560.1]
get_column("data.csv", "ticker", str)
['XEFD', 'RTRT', 'RTAT', 'RCRT', 'RTRT']
d_dict = {"A":1,"B":2}
c_dict = {"B":5}
d_dict.update(c_dict)
d_dict
{'A': 1, 'B': 5}
d_dict.update([("A",-1)])
d_dict
{'A': -1, 'B': 5}
def write_data(data, columns, filename):
with open(filename, "w") as f:
csvf =csv.writer(f)
csvf.writerow(columns)
for row in data:
csvf.writerow(row)
data = [[rows*col for col in range(5)] for rows in range(10)]
data
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12], [0, 4, 8, 12, 16], [0, 5, 10, 15, 20], [0, 6, 12, 18, 24], [0, 7, 14, 21, 28], [0, 8, 16, 24, 32], [0, 9, 18, 27, 36]]
import random
data = [[random.random() for col in range(5)] for rows in range(10)]
data
[[0.7057121257994273, 0.7864947876735638, 0.7621844085351732, 0.9654831014981514, 0.3567076740124062], [0.8881837712562509, 0.009969080535370933, 0.1288604952939728, 0.1265945416544907, 0.8881304892937462], [0.21416500435784458, 0.377220868684886, 0.33887937806712065, 0.8746205901452834, 0.6419031745768445], [0.12528488716551545, 0.759774674371733, 0.7126177864936741, 0.8896953259123864, 0.7175395149165447], [0.44668238950194983, 0.8088345273508774, 0.31607359717114136, 0.8553760127948428, 0.1539282717724595], [0.2693476517014519, 0.5667763900580283, 0.28807786366283916, 0.9799392699110685, 0.30814778875585935], [0.04268773711804652, 0.49158989964390776, 0.06243347585628645, 0.3868720211773563, 0.20015010068644956], [0.4816950723359398, 0.12721392333502135, 0.5069635425148686, 0.7357301719824074, 0.7185830726043789], [0.4981850311695367, 0.6921429602517064, 0.5359832693913509, 0.11662775529322034, 0.4055794030279445], [0.23563399202027602, 0.05107382507494951, 0.9916845405560221, 0.26444034569390906, 0.9271757106601667]]
write_data(data, list("ABCDE"), "random.csv")
!python cat.py random.csv
A,B,C,D,E 0.7057121257994273,0.7864947876735638,0.7621844085351732,0.9654831014981514,0.3567076740124062 0.8881837712562509,0.009969080535370933,0.1288604952939728,0.1265945416544907,0.8881304892937462 0.21416500435784458,0.377220868684886,0.33887937806712065,0.8746205901452834,0.6419031745768445 0.12528488716551545,0.759774674371733,0.7126177864936741,0.8896953259123864,0.7175395149165447 0.44668238950194983,0.8088345273508774,0.31607359717114136,0.8553760127948428,0.1539282717724595 0.2693476517014519,0.5667763900580283,0.28807786366283916,0.9799392699110685,0.30814778875585935 0.04268773711804652,0.49158989964390776,0.06243347585628645,0.3868720211773563,0.20015010068644956 0.4816950723359398,0.12721392333502135,0.5069635425148686,0.7357301719824074,0.7185830726043789 0.4981850311695367,0.6921429602517064,0.5359832693913509,0.11662775529322034,0.4055794030279445 0.23563399202027602,0.05107382507494951,0.9916845405560221,0.26444034569390906,0.9271757106601667
class Light:
def __init__(self):
self._status = False
def swicthon(self):
self._status = True
def swicthoff(self):
self._status = True
def status(self):
return self._status
class YellowLight(Light): # inheritence ..YellowLight is child and Light is parent
color = "Yellow" # class variable
y1 = YellowLight()
y1.status()
False
y1.color
'Yellow'
y2 = YellowLight()
class ColouredLight(Light):
def __init__(self, color):
self._status = False
self._color = color
def change_colur(self, color):
self._color = color
def get_color(self):
return self._color
c1 = ColouredLight("yellow")
c2 = ColouredLight("red")
c1.get_color()
'yellow'
c2.get_color()
'red'
y1.color
'Yellow'
y2.color
'Yellow'