Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - 如何在Python中定义二维数组(How to define a two-dimensional array in 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?

(我怎么了)

  ask by Masoud Abasian translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".

(Python将其称为“列表理解”。)

# 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".

(请注意,矩阵是“ y”地址主地址,换句话说,“ y索引”位于“ x索引”之前。)

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.

(尽管您可以根据需要命名它们,但如果您对内部和外部列表都使用“ x”,并且希望使用非平方矩阵,那么我会以这种方式来避免因索引而引起的混淆。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...