(100 days and 2 hours the next day) Nested list comprehension

Python lists can also be nested.

The following example shows a 3X4 matrix list:

1. The first way of writing

m=[[1,2,3,4],[5,6,7,8],[9,10,11,12]] #3行4列矩阵
print(m)
print([[row[i] for row in m] for i in range(4)]) #把3*4转化成4*3的矩阵

  

2. The second way of writing

m=[
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]
   ]
print(m)
t=[]
for i in range(4):
    t.append([row[i] for row in m])
print(t)

  

3. The third way of writing

m=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
print(m)
t=[]
for i in range(4):
    t_row=[]
    for row in m:
        t_row.append(row[i])
    t.append(t_row)

print(t)

  

Use nested list to convert 3*4 matrix into 4*3

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109320875