首页 > 解决方案 > 将列表列表转换为 numpy 数组

问题描述

在将此问题标记为重复之前,请通读整个帖子...

我有一个看起来像...的列表列表

>>> print(list_of_lists)
[[3, 3, 7, 8, 5], [9, 3, 3, 3, 3], [9, 10, 11, 3, 23, 3, 3], [20, 3, 3, 3, 3, 3, 3, 3], [20, 3, 3, 3, 3, 3, 3]]

我想将此列表列表转换为数组。但是,当我这样做时:

potential_numpy_array = numpy.array(list_of_lists)

或者:

potential_numpy_array = numpy.asarray(list_of_lists)

我得到了一些奇怪的东西:

>>> print(potential_numpy_array)
[list([3, 3, 17, 18, 16]) list([20, 3, 3, 3, 3]) list([20, 5, 6, 3, 12, 3, 3]) list([9, 3, 3, 3, 3, 3, 3, 3]) list([9, 3, 3, 3, 3, 3, 3])]

我查看了许多其他问题,但没有找到可以解决此问题的答案。

有人可以帮我找出混乱的根源吗?

谢谢!

标签: pythonarrayslistnumpy

解决方案


要创建一个 numpy 数组列表:

np_arrays = []

for array in arrays:
    np_arrays.append(numpy.array(array))

推荐阅读