Skip to content

Parrllel 1D Arrays

What you need to Know

You must be able to describe, exemplify and implement parallel 1D arrays.

Explanation

You already know that an array is a list of related values, called elements, that can be referred to by number, e.g. temperature[0], temperature[5] etc.

img 1

This example below now adds a second array that records the date on which the temperature was taken.

We can look up the temperature on the 8th of June, by looking for that date, and reading the corresponding temperature (14°).

These are parallel arrays, because we can look up corresponding values, like a table.

img 2

In this example, pupil marks are stored in one array, and pupil names are stored in another.

We can see that Jack scored 23, and Lucy scored 24, by looking at the two arrays side-by-side, as if they were a table.

img 3

There is no special syntax or different way to write these.

We just declare two arrays.

Example

          # Two *parallel* arrays of pupil names and marks
          pupil_name = ["Peter", "Laura", "Marie"]
          pupil_mark = [20, 21, 23]

          # If we want to find the name and mark of the third pupil in the list, we would say:
          print(pupil_name[2])
          print(pupil_mark[2])

Working with Files

This example is based on the Schools-Reg.csv file from earlier

img 4

We would implement this program with three parallel arrays - one for name, age and reg group.

This program reads the Schools.csv file, and produces an array of lines - each line of the file.

We then split each line into parts (comma separated values), e.g.:

img 5

Example

    import csv

    # Open the file for reading
    file = open("School-Reg.csv", "r")

    # Assign Parallel arrays for school reg data
    name = [str] * 3
    age = [int] * 3
    regGroup = [str] * 3

    # Loop through the array of lines
    for line in range(0, 3):
        data = file.readline()
        # Strip characters that are not required
        data = data.strip("\n")
        # Split the data on the comma
        data = data.split(",")

       # Store the 'data' in the parallel arrays
        name[line] = data[0]
        age[line] = data[1]
        regGroup[line] = data[2]

    # Display the arrays
    for i in range (0,3):
      print("Name: " + name[i] + " Age: " + str(age[i]) + " Reg: " + regGroup[i])

    # Close the file
    file.close()