[英]declaring and initialising 2d array in python
I am declaring multidimensional array in python 我在python中声明多维数组
Nbrs[23][2] = [[1, 1], [1, 2], [2, 1],
[2, 3], [3, 2], [1, 3],
[3, 1], [1, 4], [3, 4],
[4, 3], [4, 1], [1, 5],
[2, 5], [3, 5], [4, 5],
[5, 4], [5, 3], [5, 2],
[5, 1], [1, 6], [5, 6],
[6, 5], [6, 1]
]
It gives me error as: 它给我的错误是:
NameError: name 'Nbrs' is not defined
I cannot declare 2 dimensional array in python by this way? 我不能以这种方式在python中声明二维数组吗?
You don't need to specify the dimensions when defining lists in python. 在python中定义列表时,无需指定尺寸。 When you type
Nbrs[23][2]
python is trying to find what's at [23][2]
in Nbrs
but in this case Nbrs
doesn't exist because you are trying to define it for the first time here. 当您键入
Nbrs[23][2]
python会尝试查找Nbrs
中[23][2]
的Nbrs
但是在这种情况下, Nbrs
不存在,因为您是在这里首次尝试对其进行定义。
Instead do this: 而是这样做:
Nbrs = [[1, 1], [1, 2], [2, 1], ....
Assignment statement: 转让声明:
Nbrs[23][2] = [[1, 1], [1, 2], [2
# ^ ^ you can't index Nbrs before it created
should be: 应该:
Nbrs = [[1, 1], [1, 2], [2
# now after this statement, Nbrs a list of list you can access
# its elements useng `Nbrs[i][j]` for i < len(Nbrs) and j < 2
I think you confuses because of C, C++ declarations! 我认为您由于C,C ++声明而感到困惑!
That's not the right syntax. 这不是正确的语法。 You don't need to include anything about the variable's type on the left-hand side;
您无需在左侧添加任何有关变量类型的信息; in particular, drop the dimensions.
尤其要减小尺寸。
Nbrs = [[1, 1], [1, 2], [2, 1], [2, 3], [3, 2], [1, 3], [3, 1], [1, 4], [3, 4], [4, 3], [4, 1], [1, 5], [2, 5], [3, 5], [4, 5], [5, 4], [5, 3], [5, 2], [5, 1], [1, 6], [5, 6], [6, 5], [6, 1]]
What you've written tries to assign to an element of Nbrs
, which doesn't exist yet. 您编写的内容试图分配给
Nbrs
元素,该元素尚不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.