简体   繁体   English

Python展平二维列表的行

[英]Python flatten rows of 2D list

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.输出类似于: ['G', 'A', 'O', 'C', 'T']['T', 'E', 'B', 'R', 'S'] 行输出应该不再模仿列输出。 ['A', 'S', 'T', 'R', 'V', 'Y', 'V', 'B', 'B', 'G'] ['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:您可以使用extend方法大大简化cols的计算,因为内部循环遍历整个行:

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 ,但您可以使用zip使用 transpose 习惯用法:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM