Python: Is a multidimensional array (“matrix”) the same thing as lists within lists?

旧城冷巷雨未停 提交于 2020-01-15 07:44:41

问题


I'm trying to understand the differences between what people call matrices and what people call lists within lists.

Are they the same in that, once created, you can do identical things to them (reference elements the same way within them, etc).

Examples:

Making lists within a list:

ListsInLists = [[1,2],[3,4],[5,6]]

Making a multidimensional array:

np.random.rand(3,2)

Stacking arrays to make a matrix:

Array1 = [1,2,3,4]
Array2 = [5,6,7,8]
CompleteArray = vstack((Array1,Array2))

回答1:


A list of list is very different from a two-dimensional Numpy array.

  • A list has dynamic size and can hold any type of object, whereas an array has a fixed size and entries of uniform type.
  • In a list of lists, each sublist can have different sizes. An array has fixed dimensions along each axis.
  • An array is stored in a contiguous block of memory, whereas the objects in a list can be stored anywhere on the heap.

Numpy arrays are more restrictive, but offer greater performance and memory efficiency. They also provide convenient functions for vectorised mathematical operations.

Internally, a list is represented as an array of pointers that point to arbitrary Python objects. The array uses exponential over-allocation to achieve linear performance when appending repeatedly at the end of the list. A Numpy array on the other hand is typically represented as a C array of numbers.

(This answer does not cover the special case of Numpy object arrays, which can hold any kind of Python object as well. They are rarely used, since they have the restrictions of Numpy arrays, but don't have the performance advantages.)




回答2:


They are not the same. Arrays are more memory efficient in python than lists, and there are additional functions that can be performed on arrays thanks the to numpy module that you cannot perform on lists.

For calculations, working with arrays in numpy tends to be a lot faster than using built in list functions.

You can read a bit more into it if you want in the answers to this question.



来源:https://stackoverflow.com/questions/40895721/python-is-a-multidimensional-array-matrix-the-same-thing-as-lists-within-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!