# Python数组介绍和操作运算详解

## 本文概述

car1 =”兰博基尼”

car2 =”布加迪”

car3 =” Koenigsegg”

## 数组表示

• 索引从0开始。
• 我们可以通过其索引访问每个元素。
• 数组的长度定义了存储元素的能力。

## 数组运算

• 遍历-逐一打印所有元素。
• 插入-在给定的索引处添加一个元素。
• 删除-删除给定索引处的元素。
• 搜索-它使用给定的索引或值搜索元素。
• 更新-更新给定索引处的元素。

``````from array import *
arrayName = array(typecode, [initializers])``````

``````import array as arr
a = arr.array('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])``````

``````First element: 2
Second element: 4
Second last element: 8``````

## 如何更改或添加元素

``````import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element
numbers[0] = 0
print(numbers)    # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers)    # Output: array('i', [0, 2, 4, 6, 8, 10])``````

``````array('i', [0, 2, 3, 5, 7, 10])
array('i' , [0, 2, 4, 6, 8, 10])``````

## 如何从数组中删除元素？

``````import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2]                           # removing third element
print(number)                           # Output: array('i', [1, 2, 3, 4])``````

``array('i', [10, 20, 40, 60])``

## 查找数组的长度

``len(array_name)``

## 数组串联

``````a=arr.array('d', [1.1 , 2.1 , 3.1, 2.6, 7.8])
b=arr.array('d', [3.7, 8.6])
c=arr.array('d')
c=a+b
print("Array c = ", c)``````

``Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])``

``````import array as arr
x = arr.array('i', [4, 7, 19, 22])
print("First element:", x[0])
print("Second element:", x[1])
print("Second last element:", x[-1])``````

``````First element: 4
Second element: 7
Second last element: 22``````

• 回顶