如何创建空的3d多维数组

时间:2016-12-19 16:01:08

标签: python list python-3.x list-comparison

此代码是我尝试创建一个空的3d数组。

n=3
board = [[[ 0 for _ in range(n)]
            for _ in range(n)]
            for _ in range(n)]
print(board)

所以,创造的正是我正在寻找一个尺寸为n乘n乘n的3d数组,但是列表中填充了0,如果我取出0则会发生错误。我如何创建相同的列表但是空?

1 个答案:

答案 0 :(得分:1)

您需要使用[]代替0作为:

n = 5
empty_list = [[[ [] for _ in range(n)] for _ in range(n)] for _ in range(n)]

empty_list保留的值为:

[[[[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []], 
  [[], [], [], [], []]], 
# Repeated 4 more times 

例如:

>>> empty_list[0][0][0]  # Access element with nest level 3 in list
[]