[英]How to construct a numpy array to display square scheme
我想問是否可以用numpy
創建這個方案:
1 2 3
1 1
2 2
3 3
1 2 3
...然后使用命令,我將在這些數字的幫助下將“0”或“*”添加到空列,但需要在角落有空列。 如果可能我應該如何編寫代碼?
import numpy as np
n = 3 #number of elements (3 in your example)
a = np.array([[0] * (n + 2)] * (n + 2)) #creating zero-fill 2-d array
for i in range(len(a)):
for j in range(len(a[i])):
if i == 0 or i == len(a) - 1: #if we are on a border of array
if j != 0 and j != len(a[i]) - 1: #but not in corners
a[i][j] = j
if j == 0 or j == len(a[i]) - 1:# if we are on a border of array
if i != 0 and i != len(a) - 1: #but not in corners
a[i][j] = i
print(a)
要以有效的方式構造數組,使用數組索引和無循環,您可以使用:
import numpy as np
a = np.full((5, 5), ' ')
v = np.array((' ', '1', '2', '3', ' '))
a[0, :] = v
a[-1, :] = v
a[:, 0] = v
a[:, -1] = v
打印 output:
>>> for i in a:
>>> print(' '.join(i))
1 2 3
1 1
2 2
3 3
1 2 3
改編@LightVillet 的答案不那么復雜:
import numpy as np
n = 3 #number of elements (3 in your example)
a = np.full((n+2, n+2), ' ') #creating ' '-fill 2-d array
for i in range(1,n+1):
a[0,i] = i #top edge
a[n+2,i] = i #bottom edge
a[i,0] = i #left edge
a[i,n+2] = i #right edge
print(a)
復雜度: O(n)
更復雜和低效的方式,
import numpy as np
size = int(input("Please enter size of the Matrix : "))
empty = np.zeros([size,size])
numberCounter = 0
rowNumberCounter = 0
for rowCounter in range(size):
empty[rowCounter][size-1] = 0
for colCounter in range(size):
if rowCounter == 0 and colCounter == 0:
empty[rowCounter][colCounter] = 0
if rowCounter == 0 and colCounter < size-1:
empty[rowCounter][colCounter] = numberCounter
numberCounter = numberCounter + 1
if rowCounter == size-1 and colCounter != 0 and colCounter <size-1:
numberCounter = numberCounter + 1
empty[rowCounter][colCounter] = numberCounter
if rowCounter !=0 and rowCounter < size-1:
empty[rowCounter][0] = rowNumberCounter + 1
empty[rowCounter][size-1] = rowNumberCounter + 1
rowNumberCounter = rowNumberCounter + 1
numberCounter = 0
print(empty)
pushButton = input('Push * to convert 0 to * :')
if pushButton == '*':
empty_str = empty.astype(str)
for rowCounter in range(size):
for colCounter in range(size):
if empty_str[rowCounter][colCounter] == '0.0':
empty_str[rowCounter][colCounter] = '*'
print(empty_str)
Output;
Please enter size of the Matrix : 5
[[0. 1. 2. 3. 0.]
[1. 0. 0. 0. 1.]
[2. 0. 0. 0. 2.]
[3. 0. 0. 0. 3.]
[0. 1. 2. 3. 0.]]
Push * to convert 0 to * :*
[['*' '1.0' '2.0' '3.0' '*']
['1.0' '*' '*' '*' '1.0']
['2.0' '*' '*' '*' '2.0']
['3.0' '*' '*' '*' '3.0']
['*' '1.0' '2.0' '3.0' '*']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.