python中怎么定义二维数组,如何在Python中定义二维数组

I want to define a two-dimensional array without an initialized length like this:

Matrix = [][]

but it does not work...

I've tried the code below, but it is wrong too:

Matrix = [5][5]

Error:

Traceback ...

IndexError: list index out of range

What is my mistake?

解决方案

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this

"list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0

w, h = 8, 5;

Matrix = [[0 for x in range(w)] for y in range(h)]

You can now add items to the list:

Matrix[0][0] = 1

Matrix[6][0] = 3 # error! range...

Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1

x, y = 0, 6

print Matrix[x][y] # prints 3; be careful with indexing!

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值