如果你正在创建一个1d数组,你可以将它实现为一个列表,或者使用标准库中的'array'模块。我一直用链表来表示一维数组。
我想要使用数组模块的原因或情况是什么?
它是为了性能和内存优化,还是我遗漏了一些明显的东西?
如果你正在创建一个1d数组,你可以将它实现为一个列表,或者使用标准库中的'array'模块。我一直用链表来表示一维数组。
我想要使用数组模块的原因或情况是什么?
它是为了性能和内存优化,还是我遗漏了一些明显的东西?
当前回答
这是一种交易!
各有优点:
list
灵活的 可以是异质的
数组(例如:numpy数组)
统一值数组 均匀 紧凑(尺寸) 高效(功能和速度) 方便
其他回答
标准库数组对于二进制I/O非常有用,例如将整型数组转换为要写入wave文件的字符串。也就是说,正如许多人已经注意到的,如果你要做任何实际工作,那么你应该考虑使用NumPy。
Array只能用于特定类型,而list可以用于任何对象。
数组也只能有一种类型的数据,而列表可以有各种对象类型的条目。
数组对于某些数值计算也更有效。
numpy array和list之间的一个重要区别是,数组切片是原始数组的视图。这意味着数据不会被复制,对视图的任何修改都将反映在源数组中。
对于几乎所有情况,普通列表都是正确的选择。arrays模块更像是C数组上的一个薄包装器,它为您提供了一种强类型容器(参见文档),可以访问更多类似C的类型,如有符号/无符号short或double,这些都不是内置类型的一部分。我会说,只有在你真的需要它的时候才使用数组模块,在所有其他情况下,坚持使用列表。
这个答案将总结几乎所有关于何时使用List和Array的查询:
The main difference between these two data types is the operations you can perform on them. For example, you can divide an array by 3 and it will divide each element of array by 3. Same can not be done with the list. The list is the part of python's syntax so it doesn't need to be declared whereas you have to declare the array before using it. You can store values of different data-types in a list (heterogeneous), whereas in Array you can only store values of only the same data-type (homogeneous). Arrays being rich in functionalities and fast, it is widely used for arithmetic operations and for storing a large amount of data - compared to list. Arrays take less memory compared to lists.