如何访问二维数组的元素?
我想了解如何操作二维数组的元素。
例如,如果我有:
a= ( a11 a12 a13 ) and b = (b11 b12 b13)
a21 a22 a23 b21 b22 b23
我已经在 python 中定义了它们,例如:
a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]
我看到我不能引用 a[1][1]
而是引用 a[1]
这给出了 [2,1]
的结果。 所以,我不明白如何访问这些数组的第二行?那将是a21、a22、a23、b21、b22、b23
? 我该如何将它们相乘为 c1 = a21*b21, c2 = a22*b22
等?
I would like to understand how one goes about manipulating the elements of a 2D array.
If I have for example:
a= ( a11 a12 a13 ) and b = (b11 b12 b13)
a21 a22 a23 b21 b22 b23
I have defined them in python as for example:
a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]
I saw that I cannot refer to a[1][1]
but to a[1]
which gives me a result of [2,1]
.
So, I don't understand how do I access the second row of these arrays? That would be a21, a22, a23, b21, b22, b23
?
And how would I do in order to multiply them as c1 = a21*b21, c2 = a22*b22
, etc ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你有
那么
就会工作得很好。正如您想要的那样,它指向第二列、第二行。
我不确定你做错了什么。
要将第三列中的单元格相乘,您只需执行
“这适用于任意行数”的操作。
编辑:第一个数字是列,第二个数字是行,以及您当前的布局。它们都从零开始编号。如果你想切换顺序,你可以这样做
,或者你可以这样创建它:
If you have
Then
Will work fine. It points to the second column, second row just like you wanted.
I'm not sure what you did wrong.
To multiply the cells in the third column you can just do
Which will work for any number of rows.
Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do
or you can create it that way:
如果你想用二维数组做很多计算,你应该使用 NumPy 数组而不是嵌套列表。
对于您的问题,您可以使用:zip(*a) 来转置它:
If you want do many calculation with 2d array, you should use NumPy array instead of nest list.
for your question, you can use:zip(*a) to transpose it:
似乎在这里工作:
Seems to work here:
仔细看看你的数组有多少个括号。我遇到了一个例子,当函数返回带有额外括号的答案时,如下所示:
这不起作用
这可以打开括号:
现在可以使用普通的元素访问表示法:
Look carefully how many brackets does your array have. I met an example when function returned answer with extra bracket, like that:
And this didn't work
This could open the brackets:
Now it is possible to use an ordinary element access notation:
如果您有:
您可以使用以下方式轻松访问它:
If you have this :
You can easily access this by using :
a[1][1]
确实按预期工作。您的意思是 a11 作为第一行的第一个元素吗?因为那将是[0][0]。a[1][1]
does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].