📜  Python列表和数组的区别

📅  最后修改于: 2021-09-11 03:51:03             🧑  作者: Mango

列表: Python中的列表是项目的集合,它可以包含多种数据类型的元素,可以是数字、字符逻辑值等。它是一个支持负索引的有序集合。可以使用包含数据值的 [] 创建列表。
列表的内容可以使用 python 的内置函数轻松合并和复制。

# creating a list containing elements 
# belonging to different data types
sample_list = [1,"Yash",['a','e']]
print(sample_list)

输出 :

[1, 'Yash', ['a', 'e']]

第一个元素是整数,第二个元素是字符串,第三个元素是字符列表。

数组:数组是包含同类元素的向量,即属于同一数据类型。元素分配有连续的内存位置,允许轻松修改,即添加、删除、访问元素。在Python,我们必须使用array模块来声明数组。如果数组的元素属于不同的数据类型,则会抛出异常“不兼容的数据类型”。

# creating an array containing same 
# data type elements 
import array
  
sample_array = array.array('i', [1, 2, 3])  
  
# accessing elements of array
for i in sample_array:
     print(i)

输出 :

1
2
3

PythonList 和 Array 的区别如下:

List Array
Can consist of elements belonging to different data types Only consists of elements belonging to the same data type
No need to explicitly import a module for declaration Need to explicitly import a module for declaration
Cannot directly handle arithmetic operations Can directly handle arithmetic operations
Can be nested to contain different type of elements Must contain either all nested elements of same size
Preferred for shorter sequence of data items Preferred for longer sequence of data items
Greater flexibility allows easy modification (addition, deletion) of data Less flexibility since addition, deletion has to be done element wise
The entire list can be printed without any explicit looping A loop has to be formed to print or access the components of array
Consume larger memory for easy addition of elements Comparatively more compact in memory size