首頁  >  文章  >  後端開發  >  Python程式用於從數組中刪除給定數量的第一個項目

Python程式用於從數組中刪除給定數量的第一個項目

王林
王林轉載
2023-09-22 14:45:041123瀏覽

Python程式用於從數組中刪除給定數量的第一個項目

陣列是一種資料結構,用於儲存一組相同資料類型的元素。數組中的每個元素都由索引值或鍵來標識。

Python 中的陣列

Python 沒有原生的陣列資料結構。相反,我們可以使用List資料結構來表示數組。

[1, 2, 3, 4, 5]

我們也可以使用陣列或 NumPy 模組來處理 Python 中的陣列。由 array 模組定義的陣列是 -

array('i', [1, 2, 3, 4])

NumPy 模組定義的 Numpy 陣列是 -

array([1, 2, 3, 4])

Python索引是從0開始的。以上所有數組的索引都是從0開始到(n-1)。

輸入輸出場景

假設我們有一個包含 5 個元素的整數陣列。在輸出數組中,前幾個元素將被刪除。

Input array:
[1, 2, 3, 4, 5]
Output:
[3, 4, 5]

前 2 個元素 1、2 將從輸入陣列中刪除。

在本文中,我們將了解如何從陣列中刪除第一個給定數量的項目。這裡我們主要使用python切片來去除元素。

Python 中的切片

切片允許一次存取多個元素,而不是使用索引存取單一元素。

文法

iterable_obj[start:stop:step]

哪裡,

  • Start:物件切片開始的起始索引。預設值為 0。

  • End:物件切片停止處的結束索引。預設值為 len(object)-1。

  • 步長:增加起始索引的數字。預設值為 1。

使用列表

我們可以使用清單切片從陣列中刪除第一個給定數量的元素。

範例

讓我們舉個例子,應用清單切片來刪除陣列中的第一個元素。

# creating array
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

print ("The original array is: ", lst) 
print() 
numOfItems = 4
# remove first elements
result = lst[numOfItems:]
print ("The array after removing the elements is: ", result) 

輸出

The original array is:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The array after removing the elements is:  [5, 6, 7, 8, 9, 10]

從給定陣列中刪除前 4 個元素,並將結果陣列儲存在結果變數中。在此範例中,原始數組保持不變。

範例

透過使用 python del 關鍵字和切片對象,我們可以刪除陣列的元素。

# creating array
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print ("The original array is: ", lst) 
print() 
numOfItems = 4

# remove first elements
del lst[:numOfItems]
print ("The array after removing the elements is: ", lst) 

輸出

The original array is:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The array after removing the elements is:  [5, 6, 7, 8, 9, 10]

語句 lst[:numOfItems] 檢索數組中第一個給定數量的項目,del 關鍵字刪除這些項目/元素。

使用 NumPy 陣列

使用 numpy 模組和切片技術,我們可以輕鬆地從陣列中刪除項目數。

範例

在此範例中,我們將從 numpy 陣列中刪除第一個元素。

import numpy
# creating array
numpy_array = numpy.array([1, 3, 5, 6, 2, 9, 8])
print ("The original array is: ", numpy_array) 
print() 
numOfItems = 3

# remove first elements
result = numpy_array[numOfItems:]
print ("The result is: ", result) 

輸出

The original array is:  [1 3 5 6 2 9 8]

The result is:  [6 2 9 8]

我們已經使用陣列切片成功從 numpy 陣列中刪除了前 2 個元素。

使用陣列模組

Python 中的陣列模組也​​支援索引和切片技術來存取元素。

範例

在此範例中,我們將使用 array 模組建立一個陣列。

import array
# creating array
arr = array.array('i', [2, 1, 4, 3, 6, 5, 8, 7])
print ("The original array is: ", arr) 
print() 

numOfItems = 2
# remove first elements
result = arr[numOfItems:]
print ("The result is: ", result) 

輸出

The original array is:  array('i', [2, 1, 4, 3, 6, 5, 8, 7])
The result is:  array('i', [4, 3, 6, 5, 8, 7])

結果陣列已從陣列 arr 中刪除了前 2 個元素,此處陣列 arr 未變更。

以上是Python程式用於從數組中刪除給定數量的第一個項目的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除