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

PHPz
PHPz 转载
2023-09-03 22:13:06 289浏览

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函数在第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 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

元素 'i' 'j' 'k' 插入到第 0 个索引位置。

以上就是Python程序将多个元素插入到数组中的指定索引位置的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除