使用 numpy 构建序列有序列表数组的最快方法是什么?

问题描述 投票:0回答:1

就说我们从这个情况开始吧:enter image description here

蓝色数字对应位置索引

这是使用此脚本生成的:

# u v parameters allow to define how many points according to x and y

u, v = (3, 3)
x = np.linspace(0, 2, u)
y = np.linspace(0, 1, v)

# meshgrid used to create a grid out of several arrays
xx, yy, zz = np.meshgrid(x, y, 0)

# reshaping matrix
coords = np.dstack((xx,yy,zz))
coords = np.vstack(coords)

考虑到 u 和 v 可以是不同的且非常大的数字,主要目标是按照以下方案创建一个列表数组: enter image description here

意思是这样的:

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

我能够找到的解决方案与此相对应:

listing = np.array([((u)*j+i, (u)*j+i+1, (u)*j+i+u+1, (u)*j+i+u) for j in range(v-1) for i in range(u-1)])

有人能想出更好的方法(更干净、更快、更多阵列)来达到相同的结果吗?

python arrays numpy optimization
1个回答
0
投票

像这样的东西,不一定是最快的,但我认为它比你当前的版本干净得多

import numpy as np

points_indices = np.arange(9).reshape((3, 3))

quads = np.array([
    points_indices[:-1, :-1].flatten(),  # left bottom corners
    points_indices[1:, 1:].flatten(),    # right bottom corners
    points_indices[:-1, 1:].flatten(),   # top right corners
    points_indices[1:, :-1].flatten(),   # top-left corners
]).T

print(quads)
[[0 4 1 3]
 [1 5 2 4]
 [3 7 4 6]
 [4 8 5 7]]

您可能想删除这些评论。

© www.soinside.com 2019 - 2024. All rights reserved.