Python 将多个元素插入到指定索引的数组中

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 array
print("Original array:", l)

specified_index = 1
multiple_elements = 10, 11, 12

#  insert element
l[specified_index:specified_index] =  multiple_elements

print("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 array
print("Original array: ", l)

specified_index = 2
multiple_elements = list(range(1, 4))

# insert element
result = 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 函数在第二个索引位置插入了从1到4的元素。

使用 numpy.insert() 方法

在这个示例中,我们将使用 numpy.insert() 方法在给定的索引位置插入多个值。以下是语法 –

numpy.insert(arr, obj, values, axis=None)

该方法返回一个插入值的输入数组的副本。但它不会更新原始数组。

示例

在这个示例中,我们将使用 numpy.insert() 方法在第2个索引位置插入3个元素。

import numpy as np

arr = np.array([2, 4, 6, 8, 1, 3, 9])
# print initial array
print("Original array: ", arr)

specified_index = 2
multiple_elements = 1, 1, 1

#  insert element
result = 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 np
arr = np.array(['a','b', 'c', 'd'])
# print initial array
print("Original array: ", arr)
specified_index = 0
multiple_elements = list('ijk')
#  insert element
result = 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

在索引位置0处插入元素’i’、’j’、’k’。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程