java Python中的多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/508657/
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
Multidimensional array in Python
提问by Christian Stade-Schuldt
I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
我有一个小 Java 问题,我想将其转换为 Python。因此我需要一个多维数组。在 Java 中,它看起来像:
double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
Further values will be created bei loops and written into the array.
进一步的值将被创建 bei 循环并写入数组。
How do I instantiate the array?
如何实例化数组?
PS: There is no matrix multiplication involved...
PS:不涉及矩阵乘法...
回答by Barry Wark
If you restrict yourself to the Python standard library, then a list of lists is the closest construct:
如果您将自己限制在 Python 标准库中,那么列表列表是最接近的结构:
arr = [[1,2],[3,4]]
gives a 2d-like array. The rows can be accessed as arr[i]for iin {0,..,len(arr}, but column access is difficult.
给出一个类似二维的数组。该行可以作为访问arr[i]的i在{0,..,len(arr},但列的访问是困难的。
If you are willing to add a library dependency, the NumPypackage is what you really want. You can create a fixed-length array from a list of lists using:
如果您愿意添加库依赖项,那么NumPy包就是您真正想要的。您可以使用以下列表从列表中创建一个固定长度的数组:
import numpy
arr = numpy.array([[1,2],[3,4]])
Column access is the same as for the list-of-lists, but column access is easy: arr[:,i]for iin {0,..,arr.shape[1]}(the number of columns).
列访问与列表列表相同,但列访问很容易:arr[:,i]for iin {0,..,arr.shape[1]}(列数)。
In fact NumPy arrays can be n-dimensional.
事实上,NumPy 数组可以是 n 维的。
Empty arrays can be created with
可以使用创建空数组
numpy.empty(shape)
where shapeis a tuple of size in each dimension; shape=(1,3,2)gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.
其中shape是每个维度的大小元组;shape=(1,3,2)给出一个三维数组,第一维大小为 1,第二维大小为 3,第三维大小为 2。
If you want to store objects in a NumPy array, you can do that as well:
如果你想在 NumPy 数组中存储对象,你也可以这样做:
arr = numpy.empty((1,), dtype=numpy.object)
arr[0] = 'abc'
For more info on the NumPy project, check out the NumPy homepage.
有关 NumPy 项目的更多信息,请查看NumPy 主页。
回答by Deestan
To create a standard python array of arrays of arbitrary size:
创建任意大小数组的标准 python 数组:
a = [[0]*cols for _ in [0]*rows]
It is accessed like this:
它是这样访问的:
a[0][1] = 5 # set cell at row 0, col 1 to 5
A small python gotcha that's worth mentioning: It is tempting to just type
一个值得一提的小蟒蛇问题:只是输入很诱人
a = [[0]*cols]*rows
but that'll copy the samecolumn array to each row, resulting in unwanted behaviour. Namely:
但这会将相同的列数组复制到每一行,从而导致不需要的行为。即:
>>> a[0][0] = 5
>>> print a[1][0]
5
回答by Georg Sch?lly
You can create it using nested lists:
您可以使用嵌套列表创建它:
matrix = [[a,b],[c,d],[e,f]]
If it has to be dynamic it's more complicated, why not write a small class yourself?
如果它必须是动态的,那就更复杂了,为什么不自己写一个小类呢?
class Matrix(object):
def __init__(self, rows, columns, default=0):
self.m = []
for i in range(rows):
self.m.append([default for j in range(columns)])
def __getitem__(self, index):
return self.m[index]
This can be used like this:
这可以像这样使用:
m = Matrix(10,5)
m[3][6] = 7
print m[3][6] // -> 7
I'm sure one could implement it much more efficient. :)
我相信人们可以更有效地实施它。:)
If you need multidimensional arrays you can either create an array and calculate the offset or you'd use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster though…) I've implemented the first idea like this:
如果您需要多维数组,您可以创建一个数组并计算偏移量,或者您可以在数组中的数组中使用数组,这对内存来说可能非常糟糕。(虽然可能会更快......)我已经实现了这样的第一个想法:
class Matrix(object):
def __init__(self, *dims):
self._shortcuts = [i for i in self._create_shortcuts(dims)]
self._li = [None] * (self._shortcuts.pop())
self._shortcuts.reverse()
def _create_shortcuts(self, dims):
dimList = list(dims)
dimList.reverse()
number = 1
yield 1
for i in dimList:
number *= i
yield number
def _flat_index(self, index):
if len(index) != len(self._shortcuts):
raise TypeError()
flatIndex = 0
for i, num in enumerate(index):
flatIndex += num * self._shortcuts[i]
return flatIndex
def __getitem__(self, index):
return self._li[self._flat_index(index)]
def __setitem__(self, index, value):
self._li[self._flat_index(index)] = value
Can be used like this:
可以这样使用:
m = Matrix(4,5,2,6)
m[2,3,1,3] = 'x'
m[2,3,1,3] // -> 'x'
回答by Simon
Take a look at numpy
看看numpy
here's a code snippet for you
这是给你的代码片段
import numpy as npy
d = npy.zeros((len(x)+1, len(y)+1, len(x)+len(y)+3))
d[0][0][0] = 0 # although this is unnecessary since zeros initialises to zero
d[i][j][k] = npy.inf
I don't think you need to be implementing a scientific application to justify the use of numpy. It is faster and more flexible and you can store pretty much anything. Given that I think it is probably better to try and justify notusing it. There are legitimate reasons, but it adds a great deal and costs very little so it deserves consideration.
我认为您不需要实施科学应用程序来证明使用 numpy. 它更快、更灵活,您几乎可以存储任何东西。鉴于我认为尝试并证明不使用它可能更好。有正当理由,但它增加了很多,成本很低,所以值得考虑。
P.S. Are your array lengths right? It looks like a pretty peculiar shaped matrix...
PS 你的数组长度对吗?它看起来像一个非常奇特形状的矩阵......
回答by S.Lott
Multidimensional arrays are a little murky. There are few reasons for using them and many reasons for thinking twice and using something else that more properly reflects what you're doing. [Hint. your question was thin on context ;-) ]
多维数组有点模糊。使用它们的原因很少,而有很多原因需要三思而后行,使用其他更能正确反映您正在做的事情的东西。[暗示。你的问题在上下文中很薄弱;-)]
If you're doing matrix math, then use numpy.
如果你在做矩阵数学,那么使用numpy.
However, some folks have worked with languages that force them to use multi-dimensional arrays because it's all they've got. If your as old as I am (I started programming in the 70's) then you may remember the days when multidimensional arrays were the only data structure you had. Or, your experience may have limited you to languages where you had to morph your problem into multi-dimensional arrays.
然而,有些人使用的语言迫使他们使用多维数组,因为这就是他们所拥有的。如果您和我一样老(我从 70 年代开始编程),那么您可能还记得多维数组是您拥有的唯一数据结构的日子。或者,您的经验可能限制了您只能将问题转化为多维数组的语言。
Say you have a collection n3D points. Each point has an x, y, z, and time value. Is this an nx 4 array? Or a 4 * narray? Not really.
假设您有n 个3D 点的集合。每个点都有一个 x、y、z 和时间值。这是一个nx 4 阵列吗?还是一个 4 * n 的数组?并不真地。
Since each point has 4 fixed values, this is more properly a list of tuples.
由于每个点都有 4 个固定值,因此这更恰当地是一个元组列表。
a = [ ( x, y, z, t ), ( x, y, z, t ), ... ]
Better still, we could represent this as a list of objects.
更好的是,我们可以将其表示为对象列表。
class Point( object ):
def __init__( self, x, y, z, t ):
self.x, self.y, self.z, self.t = x, y, z, t
a = [ Point(x,y,x,t), Point(x,y,z,t), ... ]
回答by paprika
If you are OK using sparse arrays, you could use a dict to store your values. Python's dicts allow you to use tuples as keys, as such, you could assign to and access elements of the "sparse array" (which is really a dict here) like this:
如果您可以使用稀疏数组,则可以使用 dict 来存储您的值。Python 的字典允许您使用元组作为键,因此,您可以像这样分配和访问“稀疏数组”(这里实际上是一个字典)的元素:
d = {}
d[0,2,7] = 123 # assign 123 to x=0, y=2, z=7
v = d[0,2,7]
回答by Martin Beckett
回答by gimel
For numeric data, Numpy Arrays:
对于数字数据,Numpy Arrays:
>>> matrix1 = array(([0,1],[1,3]))
>>> print matrix1
[[0 1]
[1 3]]
For general data (e.g. strings), you can use a list of lists, list of tuples, ...
对于一般数据(例如字符串),您可以使用列表列表、元组列表、...
matrix2 = [['a','b'], ['x','y']]
回答by Rafa? Dowgird
Here's a quick way to create a nested 3-dimensional list initialized with zeros:
这是创建一个用零初始化的嵌套 3 维列表的快速方法:
# dim1, dim2, dim3 are the dimensions of the array
a =[[[0 for _ in range(dim1)] for _ in range(dim2)] for _ in range(dim1) ]
a[0][0][0] = 1
this is a list of lists of lists, a bit more flexible than an array, you can do:
这是一个列表列表,比数组更灵活,你可以这样做:
a[0][0] = [1,2,3,4]
to replace a whole row in the array, or even abuse it like that:
替换数组中的整行,甚至像这样滥用它:
a[0] = "Ouch"
print a[0][0] #will print "O", since strings are indexable the same way as lists
print a[0][0][0] #will raise an error, since "O" isn't indexable
but if you need performance, then I agree that numpy is the way to go.
但如果你需要性能,那么我同意 numpy 是要走的路。
Also, beware of:
另外,请注意:
a = [[[0] * 5]*5]*5]
If you try a[0][0][0]=7on the object above, you will see what's wrong with that.
如果你尝试a[0][0][0]=7上面的对象,你会看到它有什么问题。
回答by fabiopedrosa
I've just stepped into a similar need and coded this:
我刚刚遇到了类似的需求并对此进行了编码:
def nDimensionsMatrix(dims, elem_count, ptr=[]):
if (dims > 1):
for i in range(elem_count[dims-1]):
empty = []
ptr.append(empty)
nDimensionsMatrix(dims-1, elem_count, empty)
return ptr
elif dims == 1:
ptr.extend([0 for i in range(elem_count[dims])])
return ptr
matrix = nDimensionsMatrix(3, (2,2,2))
I'm not looking at speed, only funcionality ;)
我不看速度,只看功能;)
I want to create a matrix with N dimensions and initialize with 0 (a elem_countnumber of elements in each dimension).
我想创建一个具有 N 维的矩阵并用 0 初始化(每个维度中元素的数量为elem_count)。
Hope its helps someone
希望它可以帮助某人

