Python程序获取数组中最后给定数量的项

王林
王林 转载
2023-09-03 12:29:16 187浏览

Python程序获取数组中最后给定数量的项

数组是由许多具有相同数据类型的元素组成的数据结构,每个元素由索引标识。

[2, 4, 0, 5, 8] 

Python中的数组

Python没有自己的数据结构来表示数组。然而,我们可以使用列表数据结构作为数组的替代方案。在这里,我们将使用列表作为数组:

[10, 4, 11, 76, 99]

python 提供了一些模块来更合适地处理数组,它们是 Numpy 和数组模块。

在本文中,我们将看到从数组中访问最后给定数量的元素的不同方法。

输入输出场景

假设我们有一个包含 9 个整数值的输入数组。在输出中,最后几项是根据指定的数字进行访问的。

Input array:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[7,8,9]

从输入数组访问最后 3 项 7、8、9。

Input array:
[10, 21, 54, 29, 2, 8, 1]
Output:
[29, 2, 8, 1]

从输入数组中检索最后 4 项。

在下面的示例中,我们将主要使用Python的负索引和切片功能来检索最后几个元素。

Python 中的负索引

Python 也支持负索引,即从数组末尾开始用负号计数元素,并且从 1 开始,而不是从 0 开始。

[1, 2, 3, 4, 5]
-5 -4 -3 -2 -1

第一个元素由索引值 –n 标识,最后一个元素为 -1。

在Python中的切片

使用Python中的切片功能,可以通过最短的语法从序列中访问一组元素。

语法

sequence_object[start : end : step]
  • 开始:切片的起始索引,可迭代对象的切片起始位置,默认为0。

  • End:切片列表停止的结束索引。默认值为可迭代对象的长度。并且该值被排除在外。

使用列表

通过使用列表切片功能,我们可以访问数组中最后给定数量的元素。

示例

让我们举个例子,应用列表切片来访问数组中的最后几个元素。

# creating array
lst = [1, 2, 0, 4, 2, 3, 8] 

print ("The original array is: ", lst) 
print() 

numOfItems = 4

# Get last number of elements
result = lst[-numOfItems:]
print ("The last {} number of elements are: {}".format(numOfItems, result))

输出

The original array is:  [1, 2, 0, 4, 2, 3, 8]

The last 4 number of elements are: [4, 2, 3, 8]

使用负索引从给定数组中访问最后 4 个元素。

使用 NumPy 数组

让我们使用NumPy数组来访问最后给定数量的元素。

示例

在此示例中,我们将借助负索引值访问 numpy 数组元素。

import numpy
# creating array
numpy_array = numpy.random.randint(1, 10, 5)
print ("The original array is: ", numpy_array) 
print() 
numOfItems = 2
# get the last element
result = numpy_array[-numOfItems:]
print ("The last {} number of elements are: {}".format(numOfItems, result))

输出

The original array is:  [4 6 9 7 5]
The last 2 number of elements are: [7 5]

我们已成功访问 NumPy 数组中的最后 2 个元素。元素 7 使用 -2 进行索引,元素 5 使用 -1 进行索引。

使用数组模块

通过使用array()方法,我们将创建一个特定数据类型的数组。

示例

在此示例中,我们将使用 array 模块创建一个数组。

import array
# creating array
arr = array.array('i', [6, 5, 8, 7])
print ("The original array is: ", arr) 
print() 
numOfItems = 2
# remove last elements
result = arr[-numOfItems:]
print ("The last {} number of elements are: {}".format(numOfItems, result))

输出

The original array is:  array('i', [6, 5, 8, 7])
The last 2 number of elements are: array('i', [8, 7])

从上面的示例中,已成功访问请求的项目数。如果请求的元素数量超过序列中的元素总数,Python 切片不会生成任何错误。

以上就是Python程序获取数组中最后给定数量的项的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除