Learning Scientific Programming with Python (2nd edition)

P2.6.4: Manipulating a two-dimensional array

Question P2.6.4

Write a program to read in a two-dimensional array of strings into a list of lists from a file in which the string elements are separated by one or more spaces. The number of rows, $m$, and columns, $n$, may not be known in advance of opening the file. For example, the text file:

A B C D
E F G H
I J K L

should create an object, grid, as:

[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L']]

Read like this, grid contains a list of the array's rows. Once the array has been read in, write loops to output the columns of the array:

[['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G', 'K'], ['D', 'H', 'L']]

Harder: also output all its diagonals read in one direction:

[['A'], ['B', 'E'], ['C', 'F', 'I'], ['D', 'G', 'J'], ['H', 'K'], ['L']]

and the other direction:

[['D'], ['C', 'H'], ['B', 'G', 'L'], ['A', 'F', 'K'], ['E', 'J'], ['I']]