Currently working on a program that requires the flattening of columns, rows, and diagonals of a 2D list. I have written the following code that flattens the columns and diagonals but haven't been able to flatten the rows. I am unsure of what I am executing incorrectly.
cols = []
rows = []
max_col = len(grid[0])
max_row = len(grid)
for y in range(max_row):
rows.append(grid[y][x])
for x in range(max_col):
cols.append(grid[y][x])
print(cols)
print(rows)
firstDiagonal = [grid[i][i] for i in range(len(grid))]
secondDiagonal = [grid[i][len(grid)-1-i] for i in range(len(grid))]
The output resembles: ['G', 'A', 'O', 'C', 'T']['T', 'E', 'B', 'R', 'S'] The row output should be longer mimicking the column output. ['A', 'S', 'T', 'R', 'V', 'Y', 'V', 'B', 'B', 'G']
To flatten along the opposite dimension, you need to swap the direction of your loop. If you flatten columns by doing
cols = []
for y in range(max_row):
for x in range(max_col):
cols.append(grid[y][x])
then you flatten rows by doing
rows = []
for x in range(max_col):
for y in range(max_row):
rows.append(grid[y][x])
You can greatly simplify the computation of cols
using the extend
method, since the inner loop iterates over the entire row:
cols = []
for y in range(max_row):
cols.extend(grid[y])
Or better yet:
cols = []
for row in grid:
cols.extend(row)
Such a simplification would not work for rows
, but you can use the transpose idiom using zip
:
rows = []
for col in zip(*grid):
rows.extend(col)
Finally, each of the expressions can be written as a one-liner using any of the following nested comprehensions:
cols = [grid[y][x] for y in range(max_row) for x in range(max_col)]
cols = [item for row in grid for item in row]
rows = [grid[y][x] for x in range(max_col) for y in range(max_row)]
rows = [item for col in zip(*grid) for item in col]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.