先决条件:
数组的声明/创建
Python中数组的通用数据项和方法
以下示例演示了如何访问数组中的元素
范例1:
# 从数组访问元素 # 导入数组模块 import array as arr # 整数数组 arr1 = arr.array('i', [10, 20, 30, 40, 50, 60]) # 数组的访问元素 print("arr1[0]: ", arr1[0]) print("arr1[3]: ", arr1[3]) # 浮点数组 arr2 = arr.array('d', [22.59, 33.32, 43.32]) # 访问数组元素 print("arr2[1]: ", arr2[1]) print("arr2[2]: ", arr2[2])
输出结果
arr1[0]: 10 arr1[3]: 40 arr2[1]: 33.32 arr2[2]: 43.32
范例2:
# 导入数组模块 import array as arr # 声明int数组 arr = arr.array('i', [20, 40, 60, 80]) print("First element arr[0] :", arr[0]) print("Second element arr[1] :", arr[1]) print("Third element arr[2] :", arr[2]) print("Fourth element arr[1] :", arr[3]) print() print("Last element arr[-1]:", arr[-1]) print("Second last element arr[-2]:", arr[-2])
输出结果
First element arr[0] : 20 Second element arr[1] : 40 Third element arr[2] : 60 Fourth element arr[1] : 80 Last element arr[-1]: 80 Second last element arr[-2]: 60