Python程式移除陣列的最後一個元素


有三種不同的方法可以刪除或移除元素。讓我們逐一討論一些用於從陣列中移除最後一個元素的方法和關鍵字。

使用 Numpy 模組的 Delete() 方法

當明確指定索引時,可以使用此模組刪除陣列的元素。此操作可以透過屬於 numpy 模組的 delete() 方法來完成。但是,為了使用該 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 關鍵字還可以用於刪除列表、陣列等的元素。讓我們使用此關鍵字並刪除陣列的最後一個元素。

語法

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 ']

結論

我們可以觀察到上面討論的所有三個程式的輸出完全相同,這證明了使用所有三種方法都成功地從陣列中移除了最後一個元素。透過這種方式,可以使用簡單的技術非常輕鬆地執行陣列中任何索引的元素的刪除操作。

更新於: 2023年5月8日

6K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告