本文要介绍Python中,使用numpy对ndarray数据进行顺时针排序的方法,以及相关的示例代码。

示例数据:

import numpy as np
a1 = np.array(([2, 4, 6],
[1, 5, 3],
[7, 9, 8]))

输出结果:

np.array([[1, 2, 3],
[8, 9, 4],
[7, 6, 5]])

或者

import numpy as np
a2 = np.array(([2, 4, 6],
               [1, 5, 3],
               [7, 9, 8],
               [12, 11, 10]))

输出结果:

np.array([[1, 2, 3],
          [10, 11, 4],
          [9, 12, 5],
          [8, 7, 6]])

1、使用numpy.rot90()方法实现

import numpy as np
a1 = np.array(([2, 4, 6],
               [1, 5, 3],
               [7, 9, 8]))
def rotate(matrix, arr):
    if not len(matrix):
        return
    matrix[0] = arr[:len(matrix[0])]
    rotate(np.rot90(matrix[1:]), arr[len(matrix[0]):])
a1 = np.array(([2, 4, 6],
                [1, 5, 3],
                [7, 9, 8]))
sorted_arr = sorted(a1.ravel())
rotate(a1, sorted_arr)
print(a1)

输出结果:

[[1 2 3]
[8 9 4]
[7 6 5]]

2、使用yield和while循环实现

import numpy as np

def spiral_coords(w, h):
    maxx = w - 1
    maxy = h - 1
    minx = miny = 0
    while (minx, miny) != (maxx, maxy):
        for x in range(minx, maxx):  # right
            yield (x, miny)
        yield (maxx, miny)  # upper-right corner
        for y in range(miny + 1, maxy):  # down
            yield (maxx, y)
        yield (maxx, maxy)  # lower-right corner
        for x in range(maxx - 1, minx, -1):  # left
            yield (x, maxy)
        yield (minx, maxy)  # lower-left corner
        for y in range(maxy - 1, miny, -1):  # up
            yield (minx, y)
        minx += 1
        miny += 1
        maxx -= 1
        maxy -= 1
    yield (minx, miny)  # final point

def clockwise_sorted(a):
    a = a.T
    nr, nc = a.shape
    sa = a.ravel()
    sa.sort()
    res = np.zeros_like(a)
    for (x, y), v in zip(spiral_coords(nr, nc), sa):
        res[x, y] = v
    return res.T

a2 = np.array(
    [
        [2, 4, 6],
        [1, 5, 3],
        [7, 9, 8],
        [12, 11, 10],
    ]
)
print(a2)
print(clockwise_sorted(a2))

输出结果:

[[ 1  2  3]
[10 11 4]
[ 9 12 5]
[ 8 7 6]]

推荐文档