将具有不同长度的列表列表转换为 numpy 数组

问题描述:

我有不同长度的列表列表(例如 [[1, 2, 3], [4, 5], [6, 7, 8, 9]])并且想要转换它转换成一个 numpy 整数数组.我知道 numpy 多维数组中的子"数组必须具有相同的长度.那么将上面示例中的列表转换为 numpy 数组的最有效方法是什么 [[1, 2, 3, 0], [4, 5, 0,0], [6, 7, 8, 9]],即用零完成?

I have list of lists with different lengths (e.g. [[1, 2, 3], [4, 5], [6, 7, 8, 9]]) and want to convert it into a numpy array of integers. I understand that 'sub' arrays in numpy multidimensional array must be the same length. So what is the most efficient way to convert such a list as in example above into a numpy array like this [[1, 2, 3, 0], [4, 5, 0, 0], [6, 7, 8, 9]], i.e. completed with zeros?

你可以用 np.zeros 创建一个 numpy 数组,并用你的列表元素填充它们,如下所示.

you could make a numpy array with np.zeros and fill them with your list elements as shown below.

a = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
import numpy as np
b = np.zeros([len(a),len(max(a,key = lambda x: len(x)))])
for i,j in enumerate(a):
    b[i][0:len(j)] = j

结果

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