Python列表与阵列 - 何时使用? [英] Python List vs. Array - when to use?

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

问题描述

如果您要创建一个一维数组,你可以实现它作为一个列表,或者使用了数组模块中的标准库。我一直用列出了一维数组。

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?

推荐答案

基本上,Python列表是非常灵活的,可以容纳完全是异构的,任意数据,它们可以追加到非常有效,在的amortized恒定的时间。如果您需要收缩和增长阵列时有效,没有麻烦,他们要走的路。但是,他们使用比C数组

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 array time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays.

array.array 类型,在另一方面,是只是C数组的简单封装。它只能容纳同质数据,所有相同类型的,因此它仅使用的sizeof(一个对象)*长度字节的内存。大多数情况下,当你需要公开C数组到一个分机或系统调用(比如你应该使用它,的ioctl fctnl )。这也是重新present的好方法可变的字符串(阵列('B',字节)),直至实际的可用Python的3​​.0。

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data, 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). It's also a good way to represent a mutable string (array('B', bytes)) until that actually becomes available in Python 3.0.

不过,如果你想要做的数学数字数据的均匀阵列上,那么你就好得多使用numpy的,可以在复杂的多维数组自动矢量化操作。

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.

为了使长话短说 array.array 时,你需要考虑数据的同质数组c的是非常有用的其他不是做数学

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列表与阵列 - 何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆