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]
在这里,
- Start :对象开始切片的起始索引。默认值为0。
-
End :对象切片停止的结束索引。默认值为len(object)- 1。
-
Step :增加起始索引的数字。默认值为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数组中删除了前2个元素。
使用数组模块
Python中的数组模块也支持索引和切片技术来访问元素。
示例
在这个示例中,我们将使用数组模块创建一个数组。
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保持不变。