[英]Need to generate a 2D python list with each column having 2 possibilities, for each row
[英]How to print each row and each column simultaneously in a 2D list?
我專門想做的是:
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])
行:
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
您可以使用打印語句將它們打印出來。 我認為關鍵是要確定每一行要打印的內容。 如果矩陣是正方形,我建議跟蹤每個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)
下面的腳本產生預期的結果。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.