雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

用于从数组中删除第一个元素的 Python 程序

2024-08-17 27

为了删除数组的第一个元素,必须考虑的索引为 0,因为任何数组中第一个元素的索引始终为 0。与从数组中删除最后一个元素一样,从数组中删除第一个元素可以使用相同的技术进行处理。


让我们将这些技术应用于数组的第一个元素的删除。我们现在将讨论用于从数组中连续一个接一个地删除第一个元素的方法和关键字。


使用 pop() 方法

pop() 方法用于删除 Python 编程语言中数组、列表等的元素。此机制通过使用必须从数组中删除或删除的元素的索引来工作。


因此,要删除数组的第一个元素,请考虑索引 0。该元素只是从数组中弹出并被删除。“pop() ”方法的语法如下所述。让我们使用该方法并删除数组的第一个元素。


语法

arr.pop(0)


在此示例中,我们将讨论使用 pop() 方法删除数组的第一个元素的过程。构建此类程序的步骤如下 -


声明一个数组并在数组中定义一些元素。


通过使用 pop() 方法,提及数组的第一个索引,即方法括号内的 0 以删除第一个元素。


删除第一个元素后打印数组。


arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "] first_index = 0 print(" The elements of the array before deletion: ") print(arr) print(" The elements of the array after deletion: ") arr.pop(first_index) print(arr)


输出

上述程序的输出如下 -


The elements of the array before deletion: 

[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

The elements of the array after deletion:

[' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

使用 del 关键字

关键字 del 用于删除 Python 中的对象。此关键字还用于使用其索引删除数组的最后一个元素或任何元素。因此,我们使用此关键字来删除 Python 中的特定对象或元素。以下是此关键字的语法 -


del arr[first_index]


在下面的示例中,我们将讨论使用 “del” 关键字删除数组的第一个元素的过程。


arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "] first_index = 0 print(" The elements of the array before deletion: ") print(arr) print(" The elements of the array after deletion: ") del arr[first_index] print(arr)


输出

上述程序的输出如下 -


The elements of the array before deletion: 

[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

The elements of the array after deletion:

[' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

使用 Numpy 模块的 delete() 方法

当元素的索引被明确提及时,方法delete() 可以从数组中删除该元素。为了使用方法delete(),数组应该转换为Numpy数组的形式。也可以使用该模块执行将普通数组转换为 numpy 数组。下面描述了 delete() 方法的语法。


语法

variable = n.delete(arr, first_index)


在这个例子中,我们将讨论使用 Numpy 模块的 delete() 方法删除数组的第一个元素的过程。


import numpy as n arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "] variable = n.array(arr) first_index = 0 print(" The elements of the array before deletion: ") print(variable) variable = n.delete(arr, first_index) print(" The elements of the array after deletion: ") print(variable)


输出

上述程序的输出如下 -


The elements of the array before deletion: 

[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

The elements of the array after deletion:

[' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']

结论

我们可以清楚地观察到所有三个程序的输出都是相同的,这告诉我们通过使用所有三种方式成功地从数组中删除了数组的第一个元素。这样,使用简单的技术可以非常轻松地删除数组中任何索引的元素。如果用户知道数组元素的索引,则删除过程变得非常容易。如果不是索引,至少必须知道元素的值,以便可以应用“remove()”方法。

更新于:1个月前
赞一波!2

文章评论

全部评论