Ziy*_*her 5 python numpy list python-3.x
目前,我有一个锯齿状数组格式的3D Python列表。
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]]]。
B = numpy.array(A)然后分配并尝试B + 4引发类型错误。
TypeError: can only concatenate list (not "float") to list
是否可以从锯齿状的Python列表转换为NumPy数组,同时保留结构(我稍后需要将其转换回)还是在这种情况下循环遍历数组并添加所需的更好的解决方案?
@SonderingNarcissit 和 @MadPhysicist 的答案已经相当不错了。
这是向列表中的每个元素添加数字并保持结构的快速方法。return_number如果您不仅想添加数字还想用它做其他事情,您可以用您喜欢的任何内容替换该函数:
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]]]
Run Code Online (Sandbox Code Playgroud)
然后
print(add_number(A))
Run Code Online (Sandbox Code Playgroud)
为您提供所需的输出:
[[[4, 4, 4], [4, 4, 4], [4, 4, 4]], [[4], [4], [4]]]
Run Code Online (Sandbox Code Playgroud)
所以它的作用是递归地查找列表列表,每次找到一个数字时,它都会添加值 4;这应该适用于任意深度的嵌套列表。目前仅适用于数字和列表;如果您的列表中还有字典,那么您将必须添加另一个 if 子句。