Python程式移除陣列中前幾個元素
陣列是一種資料結構,用於儲存一組相同資料型別的元素。陣列中的每個元素都由一個索引值或鍵來標識。
Python中的陣列
Python本身沒有原生陣列資料結構。相反,我們可以使用列表資料結構來表示陣列。
[1, 2, 3, 4, 5]
我們還可以使用array或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]
從輸入陣列中移除前兩個元素1、2。
在本文中,我們將瞭解如何從陣列中移除前幾個給定數量的元素。這裡我們主要使用Python切片來移除元素。
Python中的切片
切片允許一次訪問多個元素,而不是使用索引訪問單個元素。
語法
iterable_obj[start:stop:step]
其中,
開始:切片物件開始的起始索引。預設值為0。
結束:切片物件停止的結束索引。預設值為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個元素,並將結果陣列儲存在result變數中。在這個示例中,原始陣列保持不變。
示例
透過使用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陣列中移除了前兩個元素。
使用array模組
Python中的array模組也支援索引和切片技術來訪問元素。
示例
在這個示例中,我們將使用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中移除了前兩個元素,這裡陣列arr保持不變。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP