我如何创建一个递减数组的np.零从一个起始长度在numpy

ee7vknir  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(102)

我想用numpy创建这个,而不使用python []数组:

[array([0, 0, 0, 0, 0, 0, 0])
 array([0, 0, 0, 0, 0, 0])
 array([0, 0, 0, 0, 0])
 array([0, 0, 0, 0])
 array([0, 0, 0])
 array([0, 0])
 array([0])]

字符串
目前我正在使用这个,但有一个纯粹的 numpy 方式来做到这一点?

import numpy as np

# Lengths for each array
lengths = [7, 6, 5, 4, 3, 2, 1]

# Create a NumPy universal function (ufunc) to produce arrays of zeros with specified lengths
zeros_array = np.frompyfunc(lambda x: np.zeros(x, dtype=int), 1, 1)

# Use the ufunc to create the list of NumPy arrays
arrays_list = list(zeros_array(lengths))

print(arrays_list)

bfnvny8b

bfnvny8b1#

你不需要lengths列表,你可以用range(7,0,-1)

np.frompyfunc(lambda x: np.zeros(x, dtype=int), 1, 1)(range(7,0,-1))

字符串
或如@hpaulj所建议

[np.zeros(i) for i in range(7,0,-1)]

vdgimpew

vdgimpew2#

这并不是你想要的- numpy不支持jagged arrays-但是numpy确实有掩码数组,这可以使用;

>>> np.ma.array(np.zeros((7,7)),mask=np.tril(np.ones((7,7))).T-np.eye(7))

masked_array(
  data=[[0.0, --, --, --, --, --, --],
        [0.0, 0.0, --, --, --, --, --],
        [0.0, 0.0, 0.0, --, --, --, --],
        [0.0, 0.0, 0.0, 0.0, --, --, --],
        [0.0, 0.0, 0.0, 0.0, 0.0, --, --],
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, --],
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]],
  mask=[[False,  True,  True,  True,  True,  True,  True],
        [False, False,  True,  True,  True,  True,  True],
        [False, False, False,  True,  True,  True,  True],
        [False, False, False, False,  True,  True,  True],
        [False, False, False, False, False,  True,  True],
        [False, False, False, False, False, False,  True],
        [False, False, False, False, False, False, False]],
  fill_value=1e+20)

字符串

相关问题