python 中的二维列表数组

发布于 2024-09-30 04:19:24 字数 406 浏览 2 评论 0原文

我正在尝试创建一个二维矩阵,以便每个单元格都包含一个字符串列表。

矩阵尺寸在创建之前是已知的,我需要从一开始就访问任何元素(不是动态填充矩阵)。我认为需要某种预先分配空间。

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

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

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

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

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

来操作单元格内容。

如何在Python中实现它?

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 pre-allocation 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

怂人 2024-10-07 04:19:25

这是一些扩展二维列表列表的最小示例:

my_list = [ [  [1] for x in range(4) ] for j in range(2) ]
print('initial list is ', my_list)
my_list[0][1].append(9)
print('list after extension is ', my_list)

结果是

initial list is  [[[1], [1], [1], [1]], [[1], [1], [1], [1]]]
list after extension is  [[[1], [1, 9], [1], [1]], [[1], [1], [1], [1]]]

Here's some minimal example that extends 2d list of lists:

my_list = [ [  [1] for x in range(4) ] for j in range(2) ]
print('initial list is ', my_list)
my_list[0][1].append(9)
print('list after extension is ', my_list)

and the results are

initial list is  [[[1], [1], [1], [1]], [[1], [1], [1], [1]]]
list after extension is  [[[1], [1, 9], [1], [1]], [[1], [1], [1], [1]]]

抹茶夏天i‖ 2024-10-07 04:19:25

嘿伙计们不确定这是否有帮助,但这就是我用 python3.4 生成二维列表的方式希望这有帮助

list=[]
list1=[]
list2=[]
list3=[]
answer1='yes'
answer2='yes'
answer3='yes'

while answer1=='yes':
    item1=input("Please input a list element for your first list:")
    answer1=input("Do you want to continue:")
    list1.append(item1)

while answer2=='yes':
    item2=input("Please input a list element for your second list:")
    answer2=input("Do you want to continue:")
    list2.append(item2)

while answer3=='yes':
    item3=input("Please input a list element for your third list:")
    answer3=input("Do you want to continue:")
    list3.append(item3)

list.append(list1)
list.append(list2)
list.append(list3)

print(list)

Hey guys not sure if this is helpful or not but this is how I generated a 2d list with python3.4 hope this is helpful

list=[]
list1=[]
list2=[]
list3=[]
answer1='yes'
answer2='yes'
answer3='yes'

while answer1=='yes':
    item1=input("Please input a list element for your first list:")
    answer1=input("Do you want to continue:")
    list1.append(item1)

while answer2=='yes':
    item2=input("Please input a list element for your second list:")
    answer2=input("Do you want to continue:")
    list2.append(item2)

while answer3=='yes':
    item3=input("Please input a list element for your third list:")
    answer3=input("Do you want to continue:")
    list3.append(item3)

list.append(list1)
list.append(list2)
list.append(list3)

print(list)
无言温柔 2024-10-07 04:19:24

正如您所写:

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

只需将二维矩阵视为列表的列表即可。其他操作也可以正常工作,例如,

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

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'
>>> 
热鲨 2024-10-07 04:19:24

您可以使用基本的方法来执行此操作:

matrix = [
   [["s1","s2"], ["s3"]],
   [["s4"], ["s5"]]
]

或者您可以非常通用地执行此操作

from collections import defaultdict
m = defaultdict(lambda  : defaultdict(list))
m[0][0].append('s1')

在defaultdict情况下,您有一个可以使用的任意矩阵,任何大小并且所有元素都是数组,可以进行相应的操作。

You can either do it with the basic:

matrix = [
   [["s1","s2"], ["s3"]],
   [["s4"], ["s5"]]
]

or you can do it very genericially

from collections import defaultdict
m = defaultdict(lambda  : defaultdict(list))
m[0][0].append('s1')

In the defaultdict case you have a arbitrary matrix that you can use, any size and all the elements are arrays, to be manipulated accordingly.

帝王念 2024-10-07 04:19:24

首先,您描述的实际上是一个 3 维矩阵,因为每个“单元格”也有一个维度,其 ith<​​ 的 jth 列的 kth 元素/code> 行可以通过matrix[i][j][k] 访问。

无论如何,如果您想预先分配一个 2X2 矩阵,并将每个单元格初始化为空列表,此函数将为您完成:

def alloc_matrix2d(W, H):
    """ Pre-allocate a 2D matrix of empty lists. """
    return [ [ [] for i in range(W) ] for j in range(H) ]

但是您可能认为它不起作用,因为我注意到您说您想要一个 2X2像这样的矩阵:

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

并能够使用“传统矩阵访问操作”对其执行此操作:

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

问题是,即使对于显示的矩阵也不起作用,并且对于预分配到 2X2 的矩阵仍然不起作用,因为行和列尺寸在任何一种情况下都超出范围。在 Python 中,所有序列都从零开始索引,因此具有两行各两个元素的矩阵的有效索引为 [0][0][0][1][1][0][1][1] (忽略可能在 Python 中具有特殊含义的负索引)。因此,使用Matrix[2][2]是尝试访问不存在的矩阵第三行的第三列甚至在尺寸为 2X2 的预分配空间中也不会。

如果您使用一对有效的索引值(并删除不必要的括号)将该语句更改为类似这样的内容,一切都会好起来的:

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

因为它不会引发 IndexError 反而会导致 2X2 矩阵变成:

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

奖励效用
您没有要求,但这是我编写的一个方便的函数,用于帮助打印任何类型的任意大小的二维矩阵(表示为嵌套列表):

def repr_matrix2d(name, matrix):
    lines = ['{} = ['.format(name)]
    rows = []
    for row in range(len(matrix)):
        itemreprs = [repr(matrix[row][col]) for col in range(len(matrix[row]))]
        rows.append('\n    [\n        {}\n    ]'.format(', '.join(itemreprs)))
    lines.append('{}\n]'.format(','.join(rows)))

    return ''.join(lines)

希望这会有所帮助。

First of all, what you describe is actually a 3 dimensional matrix since each 'cell' also has a dimension whose kth element of the jth column of the ith row could be accessed via matrix[i][j][k].

Regardless, if you'd like to preallocate a 2X2 matrix with every cell initialized to an empty list, this function will do it for you:

def alloc_matrix2d(W, H):
    """ Pre-allocate a 2D matrix of empty lists. """
    return [ [ [] for i in range(W) ] for j in range(H) ]

However you might think it's not working because I noticed that you said that you would like to have a 2X2 matrix like this:

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

and be able to use "traditional matrix access operations" to do this to it:

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

Problem is that won't work even for the matrix shown and still wouldn't for one preallocated to 2X2 since both the row and column dimensions are out of range in either case. In Python all sequences are indexed from zero, so valid indices for a matrix with two rows of two elements each are [0][0], [0][1], [1][0], and [1][1] (ignoring possible negative indices which have a special meaning in Python). So using Matrix[2][2] is an attempt to access the third column of the third row of the matrix which don't exist and wouldn't even in a preallocated one with dimensions of 2X2.

Everything would be fine if you changed that statement to something like this using one of the valid pairs of index values (and with unnecessary parentheses removed):

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

since it would not raise an IndexError and instead would result in the 2X2 matrix becoming:

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

Bonus Utility
You didn't ask for one, but here's a handy function I wrote to help printing out arbitrarily sized 2D matrices of any type (represented as nested lists):

def repr_matrix2d(name, matrix):
    lines = ['{} = ['.format(name)]
    rows = []
    for row in range(len(matrix)):
        itemreprs = [repr(matrix[row][col]) for col in range(len(matrix[row]))]
        rows.append('\n    [\n        {}\n    ]'.format(', '.join(itemreprs)))
    lines.append('{}\n]'.format(','.join(rows)))

    return ''.join(lines)

Hope this helps.

罪#恶を代价 2024-10-07 04:19:24

一种选择是编写自己的类,在其中重载 [] 运算符。在这里看看: http://www.penzilla.net/tutorials/python/类/
访问 1d 中的 2d 元素是 y * rowSize + x。通过编写追加函数来扩展元素,该函数将使用追加 rowSize 次。

如果您想创建一个二维矩阵并且需要预先分配,您可以执行以下操作:

x,y = 3,3
A = [ [None]*x for i in range(y) ]

您可以将 None 替换为您想要的值。您可以使用 .extend 添加附加值。

One option is to write your own class, where you overload the [] operator. Take a look for that in here: http://www.penzilla.net/tutorials/python/classes/ .
Acessing a 2d elment in 1d is y * rowSize + x. Extending the elements by writing an append function, which would use append rowSize times.

If you want to create a 2d matrix and you need to preallocate than, you could do the following:

x,y = 3,3
A = [ [None]*x for i in range(y) ]

You can replace None with the value you want. And you can use .extend to add additional values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文