如何在2D列表中同时打印每一行和每一列?

时间:2019-01-28 18:54:44

标签: python for-loop

我正在专门尝试做的事情:

2D列表:

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])

3 个答案:

答案 0 :(得分:1)

行:

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

答案 1 :(得分:0)

您可以使用打印语句将它们打印出来。我认为关键是要确定每一行要打印的内容。如果矩阵是正方形,我建议跟踪每个i的行和列。

for i in range(3):
    row = [str(matrix[i][j]) for j in range(3)]
    column = [str(matrix[j][i]) for j in range(3)]
    print("row =", ",".join(row), "column = ", ",".join(column)

答案 2 :(得分:0)

下面的脚本产生预期的结果。

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

ll_rotated = list(zip(*l1))
for row, col in zip(l1, ll_rotated):
    row_str = ','.join(map(str, row))
    col_str = ','.join(map(str, col))
    print('rows = {} column = {}'.format(row_str, col_str))

输出为:

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