您好,欢迎访问一九零五行业门户网

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。结果数组将在指定索引位置插入多个元素。
input array:[9, 3, 7, 1]output array:[9, 3, 6, 2, 10, 7, 1]
将元素 6、2、10 插入到索引位置 2 处,元素数增加到 7。
input arrays:[2 4 6 8 1 3 9]output array:[1 1 1 2 4 6 8 1 3 9]
在第0个索引位置插入了元素1 1 1。
使用列表切片要在指定索引处插入多个元素,我们可以使用列表切片。
示例在这个例子中,我们将使用列表切片。
l = [2, 3, 1, 4, 7, 5]# print initial arrayprint(original array:, l)specified_index = 1multiple_elements = 10, 11, 12# insert elementl[specified_index:specified_index] = multiple_elementsprint(array after inserting multiple elements:, l)
输出original array: [2, 3, 1, 4, 7, 5]array after inserting multiple elements: [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 initial arrayprint(original array: , l)specified_index = 2multiple_elements = list(range(1, 4))# insert elementresult = insert_elements(l, specified_index, multiple_elements)print(array after inserting multiple elements: , result)
输出original array: [1, 2, 3, 4, 5, 6]array after inserting multiple elements: [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 nparr = np.array([2, 4, 6, 8, 1, 3, 9])# print initial arrayprint(original array: , arr)specified_index = 2multiple_elements = 1, 1, 1# insert elementresult = np.insert(arr, specified_index, multiple_elements)print(array {} after inserting multiple elements at the index {} .format(result,specified_index))
输出original array: [2 4 6 8 1 3 9]array [2 4 1 1 1 6 8 1 3 9] after inserting multiple elements at the index 2
3个元素1,1,1成功插入到数组arr位置2处。
示例在此示例中,我们将使用包含所有字符串元素的 numpy 数组。
import numpy as nparr = np.array(['a','b', 'c', 'd'])# print initial arrayprint(original array: , arr)specified_index = 0multiple_elements = list('ijk')# insert elementresult = np.insert(arr, specified_index, multiple_elements)print(array {} after inserting multiple elements at the index {} .format(result,specified_index))
输出original array: ['a' 'b' 'c' 'd']array ['i' 'j' 'k' 'a' 'b' 'c' 'd'] after inserting multiple elements at the index 0
元素 'i' 'j' 'k' 插入到第 0 个索引位置。
以上就是python程序将多个元素插入到数组中的指定索引位置的详细内容。
其它类似信息

推荐信息