CMU 15-110: Principles of Computing
2d Lists
- Creating 2d Lists
- Getting 2d List Dimensions
- Nested Looping over 2d Lists
- Printing 2d Lists
- Copying 2d Lists
- Reading CSV Files
- Creating 2d Lists
- Static Allocation
# create a 2d list with fixed values (static allocation) a = [ [ 2, 3, 4 ] , [ 5, 6, 7 ] ] print(a) - Dynamic (Variable-Length) Allocation
- Wrong: Cannot use * (Shallow Copy)
# Try, and FAIL, to create a variable-sized 2d list rows = 3 cols = 2 a = [ [0] * cols ] * rows # Error: creates shallow copy # Creates one unique row, the rest are aliases! print("This SEEMS ok. At first:") print(" a =", a) a[0][0] = 42 print("But see what happens after a[0][0]=42") print(" a =", a)
- Right: make2dList()
def make2dList(rows, cols, defaultValue=None): a=[] for row in range(rows): a.append([defaultValue]*cols) return a rows = 3 cols = 2 a = make2dList(rows, cols, 0) print("This still is ok. At first:") print(" a =", a) a[0][0] = 42 print("But now see what happens after a[0][0]=42") print(" a =", a)
- Wrong: Cannot use * (Shallow Copy)
- Getting 2d List Dimensions
# Create an "arbitrary" 2d List a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ] print("a = ", a) # Now find its dimensions rows = len(a) cols = len(a[0]) print("rows =", rows) print("cols =", cols)
- Nested Looping over 2d Lists
# Create an "arbitrary" 2d List a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ] print("Before: a =", a) # Now find its dimensions rows = len(a) cols = len(a[0]) # And now loop over every element # Here, we'll add one to each element, # just to make a change we can easily see for row in range(rows): for col in range(cols): # This code will be run rows*cols times, once for each # element in the 2d list a[row][col] += 1 # Finally, print the results print("After: a =", a)
- Printing 2d Lists
def print2dList(a): # For a nicer but more complex version, see http://goo.gl/eiZ42n print('[') for row in range(len(a)): print(' ', a[row]) print(']') # Let's give the new function a try! a = [ [ 1, 2, 3 ] , [ 4, 5, 67 ] ] print2dList(a)
- Copying 2d Lists
import copy print('Ways that do not work:') a = [ [1], [2] ] b = a + [ ] c = copy.copy(a) a[0][0] = 42 print(b) # Fail! print(c) # Fail! print() print('Must use copy.deepcopy for 2d lists:') a = [ [1], [2] ] b = copy.deepcopy(a) a[0][0] = 42 print(b) # Success!
- Reading CSV Files
# Note: As this requires read-write access to your hard drive, # this will not run in the browser in Brython. def readFile(path): # This makes a very modest attempt to deal with unicode if present with open(path, 'rt', encoding='ascii', errors='surrogateescape') as f: return f.read() def readCsvFile(path): # Returns a 2d list with the data in the given csv file result = [ ] for line in readFile(path).splitlines(): result.append(line.split(',')) return result def readSampleCsvFile(): data = readCsvFile('sample.csv') # download sample.csv first! print('Reading sample.csv') rows = len(data) cols = len(data[0]) print('In sample.csv, rows =', rows, ' and cols=', cols) print('2d list of data:', data) readSampleCsvFile()
- Static Allocation