使用列表理解功能创建2D“板”-Python 3

时间:2019-05-25 11:46:08

标签: python-3.x list

我如何使用列表理解功能创建这样的板子?

board = [[(0,0), (0,1), (0,2), (0,3), (0,4)],
         [(1,0), (1,1), (1,2), (1,3), (1,4)],
         [(2,0), (2,1), (2,2), (2,3), (2,4)],
         [(3,0), (3,1), (3,2), (3,3), (3,4)],
         [(4,0), (4,1), (4,2), (4,3), (4,4)]]

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套的列表理解来实现此目标,如下所示。
在内部列表理解中为第二个索引运行for循环,在外部列表理解中为第一索引运行for循环

board = [ [(j,i) for i in range(5)] for j in range(5)]
print(board)

输出将为

[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)], 
[(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)], 
[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)], 
[(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)], 
[(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]