如何定义在python二维阵列 [英] How to define two-dimensional array in python

查看:133
本文介绍了如何定义在python二维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要定义一个二维数组没有这样一个初始化长度:

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

Matrix = [][]

,但它不工作

我想这一点,但它是错的,也:

I tried this, but it is wrong, too:

>>> Matrix = [5][5]
Traceback ...

IndexError: list index out of range

什么是我的错?

推荐答案

您正在技术上试图指数未初始化数组。你必须首先初始化添加条目之前列出了外列表; Python会自动调用此
名单COM prehension。

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

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.

这篇关于如何定义在python二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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