12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

List comprehensions are powerful tools for processing such structures, though,because they automatically scan rows and columns for us. For instance, althoughthis structure stores the matrix by rows, to collect the second column, we can simplyiterate across the rows and pull out the desired column, or iterate through positionsin the rows and index as we go:>>> [row[1] for row in M][2, 5, 8]>>> [M[row][1] for row in (0, 1, 2)][2, 5, 8]Given positions, we can also easily perform tasks such as pulling out a diagonal. Thefollowing expression uses range to generate the list of offsets, and then indexes withthe row and column the same, picking out M[0][0], then M[1][1], and so on (weassume the matrix has the same number of rows and columns):>>> [M[i][i] for i in range(len(M))][1, 5, 9]Finally, with a bit of creativity, we can also use list comprehensions to combinemultiple matrixes. The following first builds a flat list that contains the result of multiplyingthe matrixes pairwise, and then builds a nested list structure having the samevalues by nesting list comprehensions:>>> [M[row][col] * N[row][col] for row in range(3) for col in range(3)][2, 4, 6, 12, 15, 18, 28, 32, 36]>>> [[M[row][col] * N[row][col] for col in range(3)] for row in range(3)][[2, 4, 6], [12, 15, 18], [28, 32, 36]]This last expression works because the row iteration is an outer loop: for each row, itruns the nested column iteration to build up one row of the result matrix. It’s equivalentto this statement-based code:>>> res = []>>> for row in range(3):... tmp = []... for col in range(3):... tmp.append(M[row][col] * N[row][col])... res.append(tmp)...>>> res[[2, 4, 6], [12, 15, 18], [28, 32, 36]]Compared to these statements, the list comprehension version requires only one lineof code, will probably run substantially faster for large matrixes, and just might makeyour head explode! Which brings us to the next section.List Comprehensions Revisited: Mappings | 359

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!