python中的二维列表数组 [英] 2d array of lists in python

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

问题描述

我正在尝试创建一个二维矩阵,以便每个单元格都包含一个字符串列表.矩阵维度在创建之前是已知的,我需要从一开始就访问任何元素(而不是动态填充矩阵).=> 我认为需要某种预先分配的空间.

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

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

支持传统的矩阵访问操作,比如

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

tmp = 矩阵[2][2]tmp.extend('d')矩阵[2][2] = tmp

操作单元格内容.

如何在python中实现?

解决方案

正如你所写:

<预><代码>>>>矩阵 = [["str1", "str2"], ["str3"], ["str4", "str5"]]>>>矩阵[['str1', 'str2'], ['str3'], ['str4', 'str5']]>>>矩阵[0][1]'str2'>>>矩阵[0][1] += "someText">>>矩阵[['str1', 'str2someText'], ['str3'], ['str4', 'str5']]>>>矩阵[0].extend(["str6"])>>>矩阵[0]['str1', 'str2someText', 'str6']

只需将 2D 矩阵视为列表列表.其他操作也正常,例如

<预><代码>>>>矩阵[0].append('值')>>>矩阵[0][0, 0, 0, 0, 0, '值']>>>矩阵[0].pop()'价值'>>>

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.

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

or

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

to manipulate with cells content.

How to accomplish it in python?

解决方案

Just as you wrote it:

>>> 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 also work fine, for example,

>>> matrix[0].append('value')
>>> matrix[0]
[0, 0, 0, 0, 0, 'value']
>>> matrix[0].pop()
'value'
>>> 

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

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