Python 从数组中删除最后一个元素
有三种不同的方法可以删除一个元素。让我们逐一讨论一些方法和关键词,这些方法和关键词用于删除数组中的最后一个元素。
使用Numpy模块的删除()方法
可以使用此模块来删除数组的元素,当明确指定索引时。可以通过属于numpy模块的delete()方法来执行此操作。但是,为了使用该删除方法,数组应该以Numpy数组的形式创建。
Delete()方法的工作原理
delete()方法是通过指定要删除的元素的索引来删除数组或列表的元素。下面描述了使用delete()方法的语法。
语法
variable = n.delete(arr, last_index)
示例
在这个示例中,我们将讨论使用Numpy模块的delete()方法来移除数组的最后一个元素的过程。
import numpy as n
arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "]
variable = n.array(arr)
max_size = len(variable)
last_index = max_size - 1
print(" The elements of the array before deletion: ")
print(variable)
variable = n.delete(arr, last_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:
[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ']
使用“del”关键字
关键字del用于删除Python编程语言中的对象,不仅可以用于删除对象,还可以用于删除列表、数组等元素。让我们使用这个关键字并删除数组的最后一个元素。
语法
del arr[last_index]
示例
在这个示例中,我们将讨论使用del关键字来删除数组的最后一个元素的过程。
arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "]
max_size = len(arr)
last_index = max_size – 1
print(" The elements of the array before deletion: ")
print(arr)
print(" The elements of the array after deletion: ")
del arr[last_index]
print(arr)
输出
上述程序的输出结果如下:
The elements of the array before deletion:
[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']
The elements of the array after deletion:
[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ']
使用pop()方法
pop()方法用于删除Python编程语言中的数组、列表等元素。该机制利用要从数组中删除的元素的索引进行操作。元素会从数组中弹出并被移除。让我们使用这个方法并删除数组的最后一个元素。
语法
arr.pop(last_index)
示例
在这个示例中,我们将讨论使用 pop() 方法来移除数组的最后一个元素的过程。
arr = [" Hello ", " Programming ", " Python ", " World ", " Delete ", " Element "]
max_size = len(arr)
last_index = max_size -1
print(" The elements of the array before deletion: ")
print(arr)
print(" The elements of the array after deletion: ")
arr.pop(last_index)
print(arr)
输出
上述程序的输出结果如下:
The elements of the array before deletion:
[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ', ' Element ']
The elements of the array after deletion:
[' Hello ', ' Programming ', ' Python ', ' World ', ' Delete ']
结论
我们可以观察到上述三个讨论的程序的输出完全相等,这证明通过使用这三种方法,成功地从数组中删除了最后一个元素。这种方法可以通过使用简单的技术,非常容易地删除数组中任意索引的元素。