卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章21372本站已运行3413

Python程序用于从数组中删除给定数量的第一个项目

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 未更改。

卓越飞翔博客
上一篇: PHP开发技巧:如何实现用户注册和登录限制功能
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏