wshhb123
2021-06-15 09:22
采纳率: 100%
浏览 23

用Python创建一个矩阵,求详解。。。

# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)]

求解。。。

为什么这么写?中间是怎样的一个过程,一个for的推导式是理解的,但是这里主要是不理解两个for之间到底是怎么个关系和逻辑在生成。

谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 小P聊技术 2021-06-15 09:26
    已采纳

    二维列表转置:
    [row[i] for row in matrix] for i in range(matrix[0].len())]

    matrix = [
    ...     [1, 2, 3, 4],
    ...     [5, 6, 7, 8],
    ...     [9, 10, 11, 12],
    ... ]
    print(matrix)
    
    实现矩阵行列转置
    print([[row[i] for row in matrix] for i in range(4)])
    
    嵌套解析语句执行顺序同上 
    左边第二句 for i in range(4)是最外层 
    左边第一句 [row[i] for row in matrix]是最内层
    而最内层 又同样划分为 for row in matrix
    						row[i]
    因此执行顺序是
    for i in range(4)
    	for row in matrix
    		row[i]
    
    
    
    transposed = []
    for i in range(4):
        transposed.append([row[i] for row in matrix])
    print(transposed)
    
    创建二维列表格式:list_2d = [[0 for col in range(cols)] for row in range(rows)]
    list_2d = [ [0 for i in range(5)] for i in range(5)]  #创建
    print(list_2d)
    list_2d[0].append(3)
    list_2d[0].append(5)
    print(list_2d)
    
    运行结果
    [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    
    [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
    
    [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
    [[0, 0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
    
    

    列表解析详解传送门(https://www.cnblogs.com/liu-shuai/p/6098227.html)

    已采纳该答案
    1 打赏 评论

相关推荐 更多相似问题