Question Details

No question body available.

Tags

python arrays list numpy

Answers (1)

September 9, 2025 Score: 0 Rep: 16,982 Quality: Medium Completeness: 60%

The steps before, during, and after this problem statement are some mix of under-specified and undesirable. Avoid a list representation entirely. Use row-packed form, and if you are memory-constrained and can abide a 0 packing value, then you can use CSR (which will have the second dimension correct, and the first dimension as an implicit product).

import numpy as np
import scipy.sparse

nrows = 3 ncols = np.array((4, 9, 1)) nmaxcols = ncols.max() ntotalcols = ncols.sum()

rand = np.random.defaultrng(seed=0) packed = rand.random(size=(nrows, ntotalcols), dtype=np.float32)

print('If you can use this packed form directly (there are many operations that can), then STOP HERE.') np.setprintoptions(precision=7) print(packed) print()

print( "You could use this form if 0 is an acceptable padding value " "(you haven't responded to specify)." ) sparse = scipy.sparse.lil
array((nrows*ncols.size, nmaxcols)) x = 0 y = 0

There are vectorised options to construct this as well; this form is easy to understand.

for width in ncols: xnew = x + width ynew = y + nrows sparse[y: ynew, 0: width] = packed[:, x: xnew] x = xnew y = ynew csr = sparse.tocsr() print(csr.toarray())
If you can use this packed form directly (there are many operations that can), then STOP HERE.
[[0.85 0.64 0.51 0.27 0.31 0.04 0.08 0.02 0.18 0.81 0.65 0.91 0.5  0.61]
 [0.97 0.73 0.63 0.54 0.56 0.94 0.28 0.82 0.67 0.   0.39 0.86 0.55 0.03]
 [0.76 0.73 0.85 0.18 0.09 0.86 0.02 0.54 0.08 0.3  0.48 0.42 0.4  0.03]]

You could use this form if 0 is an acceptable padding value (you haven't responded to specify). [[0.85 0.64 0.51 0.27 0. 0. 0. 0. 0. ] [0.97 0.73 0.63 0.54 0. 0. 0. 0. 0. ] [0.76 0.73 0.85 0.18 0. 0. 0. 0. 0. ] [0.31 0.04 0.08 0.02 0.18 0.81 0.65 0.91 0.5 ] [0.56 0.94 0.28 0.82 0.67 0. 0.39 0.86 0.55] [0.09 0.86 0.02 0.54 0.08 0.3 0.48 0.42 0.4 ] [0.61 0. 0. 0. 0. 0. 0. 0. 0. ] [0.03 0. 0. 0. 0. 0. 0. 0. 0. ] [0.03 0. 0. 0. 0. 0. 0. 0. 0. ]]