gpt4 book ai didi

python - 用 m 和 n 整数生成围栏矩阵

转载 作者:行者123 更新时间:2023-12-04 09:33:47 25 4
gpt4 key购买 nike

当我们给出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com