Solutions

Processing a string

Your function is unlikey to be exactly the same as this but compare them to understand why we may have taken different approaches.

In [15]:
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

Re-invent the wheel

Our psuedocode, or plan for our function, is outlined below.

  1. Read specified file into list
  2. Create empty list data to hold data
  3. For each line in file a. create tmp list to store single dataset b. Split line on commas, into a list of strings c. For each data point in list
     i. Convert data point to float
     ii. Append to list created in a.
    
    d. Append tmp list to data
  4. Return data
In [16]:
def 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.