名单的二维数组在Python [英] 2d array of lists in python

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

问题描述

我试图让每个单元包含一个字符串列表来创建一个二维矩阵。
矩阵尺寸的创建之前是已知的,我需要存取从开始任何元件(未动态填充的矩阵)。 =>我觉得是需要某种空间preallocation的。

I am trying to create a 2d matrix so that each cell contains a list of strings. Matrix dimensions are known before the creation and I need to have access to any element from the beginning (not populating a matrix dynamically). => I think some kind of preallocation of space is needed.

例如,我想有一个2X2矩阵:

For example, I would like to have a 2X2 matrix:

[['A','B']          ['C'];
  ['d']       ['e','f','f']]

与支持传统矩阵访问操作,像

with support of traditional matrix access operations, like

(Matrix[2][2]).extend('d')

tmp = Matrix[2][2]
tmp.extend('d')
Matrix[2][2] = tmp

操纵与细胞的含量。

to manipulate with cells content.

如何完成它在Python?

How to accomplish it in python?

推荐答案

就像你写的:

>>> matrix = [["str1", "str2"], ["str3"], ["str4", "str5"]]
>>> matrix
[['str1', 'str2'], ['str3'], ['str4', 'str5']]
>>> matrix[0][1]
'str2'
>>> matrix[0][1] += "someText"
>>> matrix
[['str1', 'str2someText'], ['str3'], ['str4', 'str5']]
>>> matrix[0].extend(["str6"])
>>> matrix[0]
['str1', 'str2someText', 'str6']

试想一下二维矩阵列表的列表中。

Just think about 2D matrix as list of the lists.

Other operations too work just fine, like
>>> matrix[0].append('value')
>>> matrix[0]
[0, 0, 0, 0, 0, 'value']
>>> matrix[0].pop()
'value'
>>> 

这篇关于名单的二维数组在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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