如何访问二维数组的元素? [英] How to access the elements of a 2D array?

查看:45
本文介绍了如何访问二维数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何操作二维数组的元素.

I would like to understand how one goes about manipulating the elements of a 2D array.

如果我有例如:

a= ( a11 a12 a13 )  and b = (b11 b12 b13) 
     a21 a22 a23             b21 b22 b23

我已经在 python 中定义了它们,例如:

I have defined them in python as for example:

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 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 ?

推荐答案

如果你有

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

然后

a[1][1]

会正常工作.就像您想要的那样,它指向第二列第二行.

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

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

适用于任意数量的行.

第一个数字是列,第二个数字是行,使用您当前的布局.它们都从开始编号.如果你想切换顺序,你可以这样做

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

a = zip(*a)

或者你可以这样创建:

a=[[1, 2, 3], [1, 1, 1]]

这篇关于如何访问二维数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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