常用操作
常见用法
arr1 = array.array("i", [1, 2]) # 元素的字节数 print(arr1.itemsize) # 4 print(len(arr1)) # 2 # 添加元素 arr1.append(3) arr1.append(4) print(len(arr1)) # 4 print(arr1) # array('i', [1, 2, 3, 4]) # 修改元素 arr1[0] = 10 print(arr1) # array('i', [10, 2, 3, 4]) # 获取元素 print(arr1[2]) # 3 # 按元素删除 arr1.remove(10) print(len(arr1)) # 3 print(arr1) # array('i', [2, 3, 4]) # arr1.remove(20) # 删除元素, 元素不存在会抛异常 # 按索引删除 arr1.pop(0) print(len(arr1)) # 2 print(arr1) # array('i', [3, 4]) # 查找 print(arr1.index(3)) # 0 # print(arr1.index(5)) # 找不到会抛异常 print(3 in arr1) # True print(5 in arr1) # False # 插入 arr1.insert(0, 1) print(len(arr1)) # 3 print(arr1) # array('i', [1, 3, 4]) arr1.insert(1, 2) print(len(arr1)) # 4 print(arr1) # array('i', [1, 2, 3, 4]) # 遍历 for item in arr1: print(item)
其他用法
arr1 = array.array("i") # 添加可迭代对象 tuple1 = (10, 11) arr1.extend(tuple1) print(len(arr1)) # 2 print(arr1) # array('i', [10, 11]) # 添加列表 list1 = [20, 21] arr1.fromlist(list1) print(len(arr1)) # 4 print(arr1) # array('i', [10, 11, 20, 21]) arr1.append(10) # 统计出现次数 print(arr1.count(1)) # 0 print(arr1.count(10)) # 2 print(arr1.count(11)) # 1 bi = arr1.buffer_info() # 地址, 元素数量 print(type(bi), bi) # <class 'tuple'> (2430542699664, 5)
参考
python--之数组(array) - 天子骄龙 - 博客园 (cnblogs.com)
标签:10,Python,元素,len,arr1,使用,print,array From: https://www.cnblogs.com/sailJs/p/17581657.html