简体   繁体   English

不知道出什么问题了,尝试生成5x5网格python 1-25

[英]Not sure of what is wrong, trying to produce a 5x5 grid python 1-25

I am not sure what I am doing wrong, if anyone can see exactly, please inform me. 我不确定自己在做什么错,如果有人可以准确看到,请通知我。

Tried: 尝试过:

grid = [[n in range(1,6)*5]]

and

grid [[]*5 for n in range(1,25)]

My code: 我的代码:

grid = [[x for x in range(1,25)] for y in range(5)]

Output: 输出:

[[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, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [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, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]]

Desired: 期望的:

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

It's fairly obvious that values in inner lists have to be related both to internal counter in each list (x) and position of list in outer list (y). 显然,内部列表中的值必须与每个列表中的内部计数器(x)和外部列表中的列表位置 (y)相关。 Your code fails to take care about second requirement. 您的代码无法处理第二个要求。

grid = [[1+x+5*y for x in range(5)] for y in range(5)]

You are iterating in a range from 1 to 24(inclusive) in your inner loop, which is why your lists are too long, and have the same values in them. 您在内部循环中要在1到24(含)范围内进行迭代,这就是为什么列表过长,并且列表中的值相同的原因。

You somehow need to make the variable of your outer loop dictate the inner loop so each range within the inner loop start from a different point. 您需要以某种方式使外部循环的变量指示内部循环,以便内部循环中的每个范围都从不同的点开始。 Also, calibrating the length of the inner range is essential. 同样,校准内部范围的长度也是必不可少的。

That being said, I suggest the following to get your desired output. 话虽如此,我建议以下内容来获得所需的输出。

grid = [list(range(i, i+5)) for i in range(1, 26, 5)]

You can cut a list into sublist of 5, see this code 您可以将列表切成5个子列表,请参见以下代码

data=range(1,26)
len_sublist = 5
print [data[x:x+len_sublist] for x in xrange(0, len(data), len_sublist)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM