Solutions

Processing a string

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

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

Re-invent the wheel

  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
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 in lines tmp_floats .. to tmp_floats.append() with:

tmp_floats = [float(item) for item in line.split(',')]

Can you understand how this line of code is operating? This is an example of list comprehension.

How could you further improve the function? Hint: Remember that a function should contain a single unit of functionality, and compare what we have done here, with the previous exercise.