如何在 Python 中拥有一个数组数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46438039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to have an array of arrays in Python
提问by user6916458
I'm new to python, but I'm solid in coding in vb.net. I'm trying to hold numerical values in a jagged array; to do this in vb.net I would do the following:
我是 python 新手,但我在 vb.net 中编码很扎实。我试图在锯齿状数组中保存数值;要在 vb.net 中执行此操作,我将执行以下操作:
Dim jag(3)() as double
For I = 0 to 3
Redim jag(i)(length of this row)
End
Now, I know python doesn't use explicit declarations like this (maybe it can, but I don't know how!). I have tried something like this;
现在,我知道 python 不使用这样的显式声明(也许可以,但我不知道如何使用!)。我尝试过这样的事情;
a(0) = someOtherArray
a(0) = someOtherArray
But that doesn't work - I get the error Can't assign to function call. Any advice on a smoother way to do this? I'd prefer to stay away from using a 2D matrix as the different elements of a (ie. a(0), a(1),...) are different lengths.
但这不起作用 - 我收到错误无法分配给函数调用。关于更顺畅的方法有什么建议吗?我宁愿远离使用 2D 矩阵,因为 a (即 a(0), a(1),...) 的不同元素是不同的长度。
回答by
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes
锯齿状数组是其元素为数组的数组。锯齿状数组的元素可以具有不同的维度和大小
Python documentation about Data Structures.
关于数据结构的Python 文档。
You could store a list inside another list or a dictionary that stores a list. Depending on how deep your arrays go, this might not be the best option.
您可以将列表存储在另一个列表或存储列表的字典中。根据阵列的深度,这可能不是最佳选择。
numbersList = []
listofNumbers = [1,2,3]
secondListofNumbers = [4,5,6]
numbersList.append(listofNumbers)
numbersList.append(secondListofNumbers)
for number in numbersList:
print(number)
回答by Wildan Maulana Syahidillah
arr = [[]]
arr = [[]]
I'm not sure what you're trying to do, python lists is dynamically assigned, but if you want a predefined length and dimension use list comprehensions.
我不确定您要做什么,python 列表是动态分配的,但是如果您想要预定义的长度和维度,请使用列表推导式。
arr = [[0 for x in range(3)] for y in range(3)]
arr = [[0 for x in range(3)] for y in range(3)]