Python 程序从指定索引向数组插入多个元素
数组是以有组织的方式存储的同类数据元素的集合。数组中的每个数据元素都由索引值标识。
python 中的数组
Python 没有原生数组数据结构。因此,我们可以使用列表数据结构作为数组的替代。
[10, 4, 11, 76, 99]
我们还可以使用 Python Numpy 模块来处理数组。
numpy 模块定义的数组是 −
array([1, 2, 3, 4])
python 中的索引从 0 开始,因此可以使用它们各自的索引值(如 0、1、2,直到 n-1)访问上述数组元素。
在下面的文章中,我们看到了在指定索引处将多个元素插入数组的不同方法。
输入输出场景
假设我们有一个包含 4 个整数值的数组 A。并且结果数组将在指定的索引位置插入多个元素。
输入数组: [9, 3, 7, 1] 输出数组: [9, 3, 6, 2, 10, 7, 1]
元素 6、2、10 插入到索引位置 2,元素数量增加到 7。
输入数组: [2 4 6 8 1 3 9] 输出数组: [1 1 1 2 4 6 8 1 3 9]
此处元素 1 1 1 插入到第 0 个索引位置。
使用列表切片
要在指定索引处插入多个元素,我们可以使用列表切片。
示例
在此示例中,我们将使用列表切片。
l = [2, 3, 1, 4, 7, 5] # 打印初始数组 print("原始数组:", l) specified_index = 1 multiple_elements = 10, 11, 12 # 插入元素 l[specified_index:specified_index] = multiple_elements print("插入多个元素后的数组:", l)
输出
原始数组:[2, 3, 1, 4, 7, 5] 插入多个元素后的数组:[2, 10, 11, 12, 3, 1, 4, 7, 5]
使用列表连接
使用列表切片和列表连接我们将创建一个函数来在指定位置插入多个元素。Python 列表没有任何方法可以在指定位置插入多个元素。
示例
在这里我们将定义一个函数来在给定索引处插入多个元素。
def insert_elements(array, index, elements): return array[:index] + elements + array[index:] l = [1, 2, 3, 4, 5, 6] # 打印初始数组 print("原始数组: ", l) specified_index = 2 multiple_elements = list(range(1, 4)) # 插入元素 result = insert_elements(l, specified_index, multiple_elements) print("插入多个元素后的数组: ", result)
输出
原始数组:[1, 2, 3, 4, 5, 6] 插入多个元素后的数组:[1, 2, 1, 2, 3, 3, 4, 5, 6]
insert_elements 函数在第 2 个索引位置插入了从 1 到 4 的元素。
使用 numpy.insert() 方法
在此示例中,我们将使用 numpy.insert() 方法在给定的索引。以下是语法 -
numpy.insert(arr, obj, values, axis=None)
该方法返回带有插入值的输入数组的副本。但它不会更新原始数组。
示例
在此示例中,我们将使用 numpy.insert() 方法在第二个索引位置插入 3 个元素。
import numpy as np arr = np.array([2, 4, 6, 8, 1, 3, 9]) # 打印初始数组 print("原始数组: ", arr) specified_index = 2 multiple_elements = 1, 1, 1 # 插入元素 result = np.insert(arr, specified_index, multiple_elements) print("在索引 {} 处插入多个元素后的数组 {} ".format(result,specified_index))
输出
原始数组:[2 4 6 8 1 3 9] 在索引 2 处插入多个元素后的数组 [2 4 1 1 1 6 8 1 3 9]
3 个元素 1, 1, 1 成功插入到数组 arr 的位置 2。
示例
在此示例中,我们将使用包含所有字符串元素的 numpy 数组。
import numpy as np arr = np.array(['a','b', 'c', 'd']) # 打印初始数组 print("原始数组: ", arr) specified_index = 0 multiple_elements = list('ijk') # 插入element result = np.insert(arr, specified_index, multiple_elements) print("在索引 {} 处插入多个元素后的数组 {} ".format(result,specified_index))
输出
原始数组:['a' 'b' 'c' 'd'] 在索引 0 处插入多个元素后的数组 ['i' 'j' 'k' 'a' 'b' 'c' 'd']
元素 'i' 'j' 'k' 插入在第 0 个索引位置。