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()”方法。

更新於:2023年5月8日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告