Python中的5x5网格

时间:2017-10-07 14:39:02

标签: python python-3.x grid

开发人员,我想在python中创建一个5x5网格我尝试这个代码但是我无法在这里生成我需要的输出我使用abc for while循环

    l1 = []
    abc = 1
    while abc == 5:
       for i in range(1,6,1):
          l1.append(i)
           abc+=1
     print(l1)

但它只是[]

我想要这种类型的输出

['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']

2 个答案:

答案 0 :(得分:0)

由于你的while循环中有一个条件abc == 5,你的逻辑很混乱,所以它永远不会执行。你可以通过以下方式生成你想要的东西:

[[i for i in range(j, j + 5)] for j in range(0, 25, 5)]

所以输出将是:

[[0, 1, 2, 3, 4],
 [5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14],
 [15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24]]

如果您希望它从1开始并在25时结束:

[[i for i in range(j, j + 5)] for j in range(1, 26, 5)]

所以输出将是:

[1, 2, 3, 4, 5],
 [6, 7, 8, 9, 10],
 [11, 12, 13, 14, 15],
 [16, 17, 18, 19, 20],
 [21, 22, 23, 24, 25]]

更新:(根据您在问题中提供的输出)

grid = [[i for i in range(j, j + 5)] for j in range(0, 25, 5)]
for item in grid:
    print(item)

答案 1 :(得分:0)

以下是我相信你所问的问题:

class Api::TemplatesController < ApiController
  include Api::Concerns::ErrorSerializer
  ...
end

这个>>> l1 = [[i for i in range(1, 6)] for _ in range(5)] >>> print(*l1, sep='\n') [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] >>> 成语非常简单,可以在Python shell中记忆和使用,并且想要快速检查二维列表。