Python 删除数组的第一个元素
为了删除数组的第一个元素,必须考虑索引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() ”方法。