python矩阵数量增加
我的问题是我需要一个2维数组,该数组将值1保持在矩阵的中心,然后从那时开始其他数字。例如,当输入为3时,矩阵应该看起来像这样:
[[3, 3, 3, 3, 3],
[3, 2, 2, 2, 3],
[3, 2, 1, 2, 3],
[3, 2, 2, 2, 3],
[3, 3, 3, 3, 3]]
这是我的代码到目前为止:
import pprint
def func(number):
d = [[0] for i in range(number + (number - 1))]
#? Create the matrix with 0 value inside each index and determine the amount of columns
for i in d:
d[d.index(i)] = [number] * (number + (number - 1))
#? Add values to the indexes
#? [value inside] * [length of a row]
centre = len(d) // 2
#? centre is the index value of the list which contains the number 1
pprint.pprint(d)
func(3)
结果是:
[[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]]
我的方法是在整个桌子上填充给定的数字,然后使用桌子的其余部分工作第一个也是最后一个数组,因为它们不会更改,其价值将始终是必要的数量。
我什至知道中心是2D阵列的索引。但是,我被困在这里。我不确定如何从这里继续。
My problem here is that I need a 2 dimensional array, that holds the value 1 in the center of the matrix and then other numbers continue from that point. For example, when the input is 3, the matrix should look like this:
[[3, 3, 3, 3, 3],
[3, 2, 2, 2, 3],
[3, 2, 1, 2, 3],
[3, 2, 2, 2, 3],
[3, 3, 3, 3, 3]]
This is my code so far:
import pprint
def func(number):
d = [[0] for i in range(number + (number - 1))]
#? Create the matrix with 0 value inside each index and determine the amount of columns
for i in d:
d[d.index(i)] = [number] * (number + (number - 1))
#? Add values to the indexes
#? [value inside] * [length of a row]
centre = len(d) // 2
#? centre is the index value of the list which contains the number 1
pprint.pprint(d)
func(3)
The result is this:
[[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]]
My approach was to fill the whole table with the number given, then work with the rest of the table without the first and last array, because they won't change and their value will always be the number times amount necessary.
I even know at what index of the 2D array the center is. However, I am stuck here. I'm not sure how to continue from here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个索引处的值由最大值(从行索引到中心的距离,从列索引到中心的距离)。因此,您可以做:
这输出:
The value at each index is given by the maximum of (distance from the row index to the center, distance from the column index to the center). So, you can do:
This outputs:
有趣的问题!
这就是我的想法。它比您的实现要短得多:
输出如您所愿!可能可以对此进行更多调整。
说明:
它首先创建一个维度为
mdim
的零矩阵。然后,它使用
0:5
行和0:5
列的v=3
值填充矩阵。它依次用
1:4
行和1:4
列的v-1=2
值填充矩阵,直到中心得到1
的最终值。Fun question!
Here's what I came up with. It's quite shorter than your implementation:
The output is as desired! It's probably possible to tweak this a little bit more.
Explanations:
It first creates a matrix of zeros with the dimensions of
mdim
.Then, it fills the matrix with the values of
v=3
from rows0:5
and columns0:5
.It successively fills the matrix with the values of
v-1=2
from rows1:4
and columns1:4
, until the centre gets the final value of1
.