本文介绍了Python 列表与数组 - 何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你正在创建一个一维数组,你可以将它实现为一个列表,或者使用标准库中的数组"模块.我一直对一维数组使用列表.

我想改用数组模块的原因或情况是什么?

是为了性能和内存优化,还是我遗漏了一些明显的东西?

解决方案

基本上,Python 列表非常灵活,可以容纳完全异构的任意数据,并且可以非常有效地附加到 摊销常数时间.如果您需要既省时又省力地缩小和扩大您的清单,那么它们就是您要走的路.但是它们使用比 C 数组更多的空间,部分原因是列表中的每一项都需要构建一个单独的 Python 对象,即使对于可以用简单的 C 类型表示的数据(例如 floatuint64_t).

另一方面,array.array 类型只是 C 数组的一个薄包装.它只能容纳同类数据(即所有相同类型的数据),因此它仅使用 sizeof(one object) * length 字节的内存.大多数情况下,您应该在需要将 C 数组公开给扩展或系统调用(例如,ioctlfctnl)时使用它.

array.array 也是在 Python 2.x 中表示 可变 字符串的合理方式 (array('B', bytes)).然而,Python 2.6+ 和 3.x 提供了一个可变的byte 字符串作为 bytearray.

但是,如果您想对同构的数值数据数组进行数学,那么最好使用 NumPy,它可以自动对复杂的多维数组进行矢量化操作.>

长话短说:array.array 在您需要一个同构的 C 数据数组时非常有用数学运算以外的原因.

If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.

What is the reason or circumstance where I would want to use the array module instead?

Is it for performance and memory optimization, or am I missing something obvious?

解决方案

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

这篇关于Python 列表与数组 - 何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 14:59