数组是由许多具有相同数据类型的元素组成的数据结构,每个元素由索引标识。
[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 arraylst = [1, 2, 0, 4, 2, 3, 8] print (the original array is: , lst) print() numofitems = 4# get last number of elementsresult = 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 arraynumpy_array = numpy.random.randint(1, 10, 5)print (the original array is: , numpy_array) print() numofitems = 2# get the last elementresult = 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 arrayarr = array.array('i', [6, 5, 8, 7])print (the original array is: , arr) print() numofitems = 2# remove last elementsresult = 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程序获取数组中最后给定数量的项的详细内容。