1. 增加元素
# 普通数组
a = [1, 2, 3]
a.append(4)
print(a) # output: [1, 2, 3, 4]
# Numpy 数组
a2 = np.array([1, 2, 3])
aa2 = np.append(a2, 5)
print(aa2) # output: [1 2 3 5]
2. 插入元素
# 普通数组
a = [1, 2, 3]
a.insert(1, 33)
print(a) # output: [1, 33, 2, 3]
# Numpy数组
a2 = np.array([1,2,3])
a3 = np.insert(a2, 1, 33)
print(a3) # output: [1 33 2 3]
3. 删除元素
# 普通数组
a = [1, 2, 3]
a.remove(3) # 删除值是3的第一个元素
print(a) # output: [1, 2]
-----------------------------
a = [1, 2, 3]
a.pop(1) # 删除索引是1的元素
print(a) # output: [1, 3]
print(a.pop(1)) # output: 3
-----------------------------
a = [1, 2, 3, 4]
del a[0:2]
print(a) # output: [3, 4]
# Numpy数组
a2 = np.array([1,2,3])
a3 = np.delete(a2, 0) # 删除索引的值
print(a3) # output: [2 3]
4. 修改元素(普通数组和Numpy数组,修改方式一致)
# 普通数组,修改元素
a = [1, 2, 3, 4]
a[0] = 5
print(a) # output [5, 2, 3, 4]
# Numpy数组,修改元素
a2 = np.array([1,2,3,4])
a2[0] = 5
print(a2) # output [5 2 3 4]
5. 查找元素
# 普通数组
a = [1,2,3,4]
index = a.index(3)
print(index) # output: 2
# Numpy数组
a2 = np.array([1,2,3,4])
index = np.where(a2 == 2)
print(index[0][0]) # output: 1
网友评论