简体   繁体   中英

Creating a python array where the outside elements increase in chronological order

I want to create a python array like this:

[[1, 10, 9, 8]
 [2, 0, 0, 7]
 [3, 4, 5, 6]] 

However, I want to do it with a function so if the dimensions of the array change I still get the same output, where the outside elements increase numerically and the middle elements stay as zero.

this is an attempt with N and M as height and width:

N = 5
M = 7

m = []

# first row
m.append([1] + list(range(2*N + 2*M - 4, M + 2*N - 3, -1)))

# middle rows
for i in range(1, N-1):
    row = M*[0]
    row[0] = i+1
    row[-1] = 2*N + M -2 - i
    m.append(row)

# last row
m.append(list(range(N, N+M)))

for row in m:
    strgs = ('{:2d}'.format(n) for n in row)
    print(' '.join(strgs))

it prints:

 1 20 19 18 17 16 15
 2  0  0  0  0  0 14
 3  0  0  0  0  0 13
 4  0  0  0  0  0 12
 5  6  7  8  9 10 11

as requested the very same in numpy

import numpy as np

m =  np.zeros(shape=(N, M), dtype=int)

# first row
m[0] = [1] + list(range(2*N + 2*M - 4, M + 2*N - 3, -1))

# middle rows
for i, row in enumerate(m[1:-1], start=2):
    row[0] = i
    row[-1] = 2*N + M -1 - i

# last row
m[-1] = list(range(N, N + M))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM