作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我们给出 m 和 n 正整数时,如何生成一个以边界 1 和 0 为核心的矩阵。
Input:
4,5
Output
[1, 1, 1, 1, 1]
[1, 0, 0, 0, 1]
[1, 0, 0, 0, 1]
[1, 1, 1, 1, 1]
我用了这段代码。有没有其他方法可以得到输出
import numpy as np
a=np.ones((m,n),dtype="int")
a[1:-1,1:-1]=0
最佳答案
另一个类似的解决方案,但我更喜欢问题中建议的解决方案:
a=np.zeros((m,n),dtype="int")
a[[0,-1]] = 1
a[:,[0,-1]] = 1
或者根据@Paul 在评论中的建议:
a[::m-1] = a[:,::n-1] = 1
编辑 :根据OP的评论如下:
a = [x for x in a]
列表数组:
b = np.empty(m,dtype=object)
b[:] = a.tolist()
关于python - 用 m 和 n 整数生成围栏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62689809/
我是一名优秀的程序员,十分优秀!