列表是 python 程序中最常用的数据结构之一。在这篇文章中,我们将研究在Python中获取列表中最后一个元素的不同方法。为此,我们将使用索引、pop()方法、切分和反向迭代器等方法。
使用Python中的索引获取列表的最后一个元素
python中的索引是一种访问列表中元素的方法。在Python中,我们可以使用正指数和负指数。正指数从零开始,对应于列表的第一个元素,列表的最后一个元素由指数 "listLen-1 "标识,"listLen "是列表的长度。
另外,负指数从-1开始,对应于列表的最后一个元素。它一直到"-listLen",其中listLen是列表的长度。索引"-listLen "对应于列表中的第一个元素。
要获得一个列表的最后一个元素,我们可以首先使用 len() 函数找到该列表的长度。然后我们可以在索引 "listLen-1 "处访问列表中的最后一个元素,方法如下。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
listLen = len(myList)
lastElement = myList[listLen - 1]
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
或者,我们可以使用负数索引来访问列表的最后一个元素。列表的最后一个元素在索引-1处,可以按如下方式访问。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList[- 1]
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
我们可以看到,在使用负数索引时,我们不需要计算列表的长度。
使用pop()方法
pop()方法是用来从列表中移除指定索引的任何元素。它将元素的索引作为一个可选的输入参数,并在从列表中删除该元素后返回指定索引的元素。如果没有传递输入参数,它将在删除后返回列表中的最后一个元素。
我们可以使用pop()方法来获得列表的最后一个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList.pop()
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
记住,pop()方法也会删除被访问的元素。所以,只有当你想删除列表的最后一个元素时才使用这个方法。
在 Python 中使用切片法获取列表的最后一个元素
在 python 中,切片是一种创建字符串或列表的子部分的操作。通过切分,我们可以访问任何字符串、元组或列表的不同部分。要对一个命名的列表进行切片,我们使用 listName[start, end,interval] 语法,其中 "start" 和 "end" 分别是被切片的列表在原始列表中开始和结束的索引。间隔 "用于选择序列中的元素。从列表中选择的元素是离开始索引的 "间隔 "的整数倍的索引。
在 python 中使用切分来访问一个列表的最后一个元素,我们可以将一个列表切分到只包含最后一个元素。然后我们可以按如下方式访问该元素。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = myList[-1:][0]
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
使用反向迭代器获取列表的最后一个元素
我们可以使用反向迭代器来获取列表的最后一个元素。为了创建一个反向迭代器,我们可以使用 reversed() 方法。reversed()方法接受任何可迭代对象作为输入,并返回该可迭代对象的反向迭代器。
为了得到一个列表的最后一个元素,我们将首先使用reversed()方法创建一个列表的反向迭代器。然后我们将访问反向迭代器的第一个元素,这将是原始列表的最后一个元素。这可以按以下方式进行。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
reverseIter = reversed(myList)
lastElement = next(reverseIter)
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
使用 itemgetter 获取列表的最后一个元素
我们可以创建一个 itemgetter 对象来访问列表的最后一个元素。itemgetter() 方法是在 python 的 operator 模块中定义的。itemgetter() 方法将索引作为输入,创建一个可调用对象。这个可调用对象将一个迭代器作为输入,并提取指定索引处的元素。
为了访问列表的最后一个元素,我们可以调用 itemgetter() 方法,输入索引为 -1,然后我们可以访问列表的最后一个元素,如下所示。
import operator
myList = [1, 2, 3, 4, 5, 6, 7]
print("Given List is:", myList)
lastElement = operator.itemgetter(-1)(myList)
print("Last element of the list is:", lastElement)
输出。
Given List is: [1, 2, 3, 4, 5, 6, 7]
Last element of the list is: 7
结论
在这篇文章中,我们已经看到了在 python 中获取列表最后一个元素的不同方法。要阅读更多关于列表的内容,请阅读这篇关于 Python 中列表理解的文章。请继续关注更多内容丰富的文章。
The postGet the last element of a list in Pythonappeared first onPythonForBeginners.com.