如何定义二维数组?

编程入门 行业动态 更新时间:2024-10-19 04:21:37
本文介绍了如何定义二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想定义一个二维数组,而没有这样的初始化长度:

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

Matrix = [][]

但它不起作用...

我已经尝试过下面的代码,但这也是错误的:

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

Matrix = [5][5]

错误:

Traceback ... IndexError: list index out of range

我怎么了?

推荐答案

从技术上讲,您正在尝试索引未初始化的数组.您必须先使用列表初始化外部列表,然后再添加项目.Python 调用这个列表理解".

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)]

您现在可以将项目添加到列表中:

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

请注意,矩阵是"y"地址主地址,换句话说,"y索引"位于"x索引"之前.

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!

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

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.

更多推荐

如何定义二维数组?

本文发布于:2023-11-29 21:38:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!