Your function is unlikey to be exactly the same as this but compare them to understand why we may have taken different approaches.
def process_string(datum):
'''
Take parameter as string of form
"Firstname Surname Mark1 Mark2 Total"
1. Split into a list
2. Convert Marks and total to integers
and return list in form:
["Firstname", "Surname", Mark1, Mark2, Total]
'''
tmp_list = datum.split()
for i_list in range(2,5):
tmp_list[i_list] = int( tmp_list[i_list] )
return tmp_list
Our psuedocode, or plan for our function, is outlined below.
i. Convert data point to float
ii. Append to list created in a.
d. Append tmp list to datadef read_csv_to_floats(filename):
'''
Take string parameters as csv filename.
Read in and process file, converting all elements to floats.
Return as 2D list (list of lists)
'''
with open(filename) as file:
data_string = file.readlines()
data_floats = []
for line in data_string:
tmp_floats = []
tmp_list = line.split(',')
for item in tmp_list:
tmp_floats.append( float(item) )
data_floats.append(tmp_floats)
return data_floats
This can be made more 'pythonic still by replacing the code for 'a, b, c, d', lines tmp_floats ..
to tmp_floats.append()
with:
tmp_floats = [float(item) for item in line]
Can you understand how this line of code is operating? How could you further improve the function?
Hint: Remember that a function should contain a single unit of functionality, and compate what we have done here, with the previous exercise.