python - using 1's in the arrays to make a shape like '+' using numpy in python
问题描述
Numpy Three Four Five Dimensional Array in Python
Input 1: 3
Output 1:
[[0 1 0]
[1 1 1]
[0 1 0]]
Input 2:5
Output 1:
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
Notice that the 1s in the arrays make a shape like +.
My logic is shown below
a=np.zeros((n,n),dtype='int')
a[-3,:] = 1
a[:,-3] = 1 print(a)
This logic is only working for five dimensional array but not for three dimensional array.
can someone assist me to get the expected output for both three and five dimensional array using np.zeros
& integer division //
解决方案
如您所见,n//2 = 3
当n=5
. 因此,这就是您的问题的解决方案,如下所示:
import numpy as np
def create_plus_matrix(n):
a = np.zeros((n,n),dtype='int')
a[-n//2,:] = 1
a[:,-n//2] = 1
return a
所以,让我们尝试一下:
>>> create_plus_matrix(3)
[[0 1 0]
[1 1 1]
[0 1 0]]
>> create_plus_matrix(5)
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
推荐阅读
- android - 使用动态数据解析非常大的 JSON 文件
- python - 根据字典值打印单数/复数
- powershell - Powershell Invoke-Command 未使用 Get-Clipboard 抓取剪贴板数据
- mongodb - 在哪里存储用户在论坛上上传的照片的最佳位置
- syntax - 为什么有时一个变量在匹配中被取消引用?
- c - 传递 unix c 语言参数和参数值
- matplotlib - Matplotlib gridspec 指定子图布局时遇到问题
- arduino - Arduino 错误:从 'const char*' 到 'char*' 的无效转换 [-fpermissive]
- python - 按内部数组的长度降序对二维数组进行排序?
- opencv - OpenCV圆形遮罩抗锯齿