numpy元组的2D数组



我想从两个列表的笛卡尔乘积创建一个2D numpy数组。

from itertools import product
b1 = 25
b2 = 40
step = 2
lt1 = range(1,b1+1,step)
lt2 = range(1,b2+1,step)
func(product(lt1,lt2,repeat=1))

我希望函数创建一个2D numpy数组,这样条目就是元组对。

例如,如果lt1 = [2,3]lt2 = [1,4,7],那么2D阵列应该是

[ [(2,1), (2,4), (2,7)],
[(3,1), (3,4), (3,7)] ]

我的最终目标是从数组中创建固定大小的块,并检索与块元组对应的值(从以键为元组的列表字典中(,并消除一些块。

有什么帮助吗?

我希望我能正确理解你的问题。要创建整数元组的2D numpy数组,可以执行以下操作:

from itertools import product
lt1 = [2, 3]
lt2 = [1, 4, 7]
arr = np.array([*product(lt1, lt2)], dtype=("i,i")).reshape(len(lt1), len(lt2))
print(arr)

打印:

[[(2, 1) (2, 4) (2, 7)]
[(3, 1) (3, 4) (3, 7)]]

最新更新