将3D列表转换为3D NumPy数组 [英] Converting a 3D List to a 3D NumPy array

查看:101
本文介绍了将3D列表转换为3D NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个锯齿状数组格式的3D Python列表.
A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]

Currently, I have a 3D Python list in jagged array format.
A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]

有什么方法可以将此列表转换为NumPy数组,以便使用某些NumPy数组运算符,例如为每个元素添加一个数字.
A + 4会给出[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]].

Is there any way I could convert this list to a NumPy array, in order to use certain NumPy array operators such as adding a number to each element.
A + 4 would give [[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]].

分配B = numpy.array(A)然后尝试B + 4会引发类型错误.
TypeError: can only concatenate list (not "float") to list

Assigning B = numpy.array(A) then attempting to B + 4 throws a type error.
TypeError: can only concatenate list (not "float") to list

是否可以从锯齿状的Python列表转换为NumPy数组,同时保留结构(我稍后需要将其转换回去),或者在这种情况下循环遍历数组并添加所需的更好的解决方案?

Is a conversion from a jagged Python list to a NumPy array possible while retaining the structure (I will need to convert it back later) or is looping through the array and adding the required the better solution in this case?

推荐答案

@SonderingNarcissit和@MadPhysicist的答案已经相当不错了.

The answers by @SonderingNarcissit and @MadPhysicist are already quite nice.

这里是将数字添加到列表中的每个元素并保留结构的快速方法.如果您不仅想添加数字,还想做其他事情,则可以用任何喜欢的功能代替return_number:

Here is a quick way of adding a number to each element in your list and keeping the structure. You can replace the function return_number by anything you like, if you want to not only add a number but do something else with it:

def return_number(my_number):
    return my_number + 4    

def add_number(my_list):

    if isinstance(my_list, (int, float)):
        return return_number(my_list)
    else:
        return [add_number(xi) for xi in my_list]

A = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0], [0], [0]]]

然后

print(add_number(A))

为您提供所需的输出:

[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]]

所以它的作用是在列表列表中递归查找,每当找到一个数字时,它就会将值加4.这应该适用于任意深度的嵌套列表.目前仅适用于数字和列表.如果您还有列表中还有字典,那么您将不得不添加另一个if子句.

So what it does is that it look recursively through your list of lists and everytime it finds a number it adds the value 4; this should work for arbitrarily deep nested lists. That currently only works for numbers and lists; if you also have e.g. also dictionaries in your lists then you would have to add another if-clause.

这篇关于将3D列表转换为3D NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆