首页 > 解决方案 > 如何在二维列表中同时打印每一行和每一列?

问题描述

我具体想做的是:

二维列表:

l1 = [[2,4,5],
      [5,7,5],
      [1,9,7]]

我希望输出为:

row = 2,4,5 column = 2,5,1
row = 5,7,5 column = 4,7,9
row = 1,9,7 column = 5,5,7

这就是我所拥有的:

x = -1
for i in range(3):
    x+=1
    print(l1[i], end="")
    print(l1[x][i])

标签: pythonfor-loop

解决方案


行:

rows = l1
Output: [[2, 4, 5], [5, 7, 5], [1, 9, 7]]

科尔斯:

cols = [[row[i] for row in l1] for i in range(col_length)]
Output: [[2, 5, 1], [4, 7, 9], [5, 5, 7]]

或如评论中所述:

cols = list(zip(*rows))
Output: [(2, 5, 1), (4, 7, 9), (5, 5, 7)]

压缩和操作:

>>> for row, col in zip(rows, cols):
...     print(str(row), str(col))
... 
[2, 4, 5] [2, 5, 1]
[5, 7, 5] [4, 7, 9]
[1, 9, 7] [5, 5, 7]

>>> for row, col in zip(rows, cols):
...     print("rows = {} columns = {}".format(",".join(map(str, row)), ",".join(map(str, col))))
... 
rows = 2,4,5 columns = 2,5,1
rows = 5,7,5 columns = 4,7,9
rows = 1,9,7 columns = 5,5,7

推荐阅读