Python数组
注意: Python不具有对数组的内置支持,但是可以使用Python列表代替。
数组
注意:此页面显示了如何将LISTS用作数组,但是,要在Python中使用数组,您必须导入一个库,例如NumPy library。
数组用于将多个值存储在一个变量中:
什么是数组?
数组是一个特殊变量,一次可以容纳多个值。
如果有项目列表(例如,汽车名称列表),则将汽车存储在单个变量中可能如下所示:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
但是,如果您想遍历汽车并找到特定的汽车怎么办?如果您没有3辆车,却有300辆车怎么办?
解决方案是数组!
数组可以用一个名称保存许多值,并且您可以通过引用索引号来访问这些值。
访问数组的元素
您可以通过引用索引号来引用数组元素。
数组的长度
使用该len()
方法返回数组的长度(数组中元素的数量)。
注意:数组的长度总是比最高数组索引大一。
循环数组元素
您可以使用for in
循环遍历数组的所有元素。
添加数组元素
您可以使用该append()
方法将元素添加到数组。
删除数组元素
您可以使用该pop()
方法从数组中删除一个元素。
您也可以使用该remove()
方法从数组中删除元素。
注意:列表的remove()
方法仅删除指定值的第一次出现。
数组方法
Python有一组内置方法,可用于列表/数组。
Method | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
注意: Python不具有对数组的内置支持,但是可以使用Python列表代替。