在Python中访问列表的最后一个元素
我有一个列表,比如说:list_a = [0,1,3,1]
我想要逐个查看这个列表里的每个数字,如果遇到最后一个“1”,就打印出“这是列表中的最后一个数字”。
因为列表里有两个“1”,那么有什么方法可以找到最后那个“1”呢?
我试过:
if list_a[-1] == 1:
print "this is the last"
else:
# not the last
但这个方法不行,因为第二个元素也是“1”。我又试过:
if list_a.index(3) == list_a[i] is True:
print "this is the last"
但是这个方法也不行,因为列表里有两个“1”。
5 个回答
2
在Python 2.7.3上测试过
这个方法适用于任何大小的列表。
list_a = [0,1,3,1]
^ 我们定义了一个叫做 list_a
的列表。
last = (len(list_a) - 1)
^ 我们计算列表中元素的数量,然后减去1。这就是最后一个元素的位置。
print "The last variable in this list is", list_a[last]
^ 我们展示这些信息。
17
list_a[-1]
是获取列表最后一个元素的方法。
7
你可以使用 enumerate 来同时遍历列表中的每个项目和这些项目的索引。
for idx, item in enumerate(list_a):
if idx == len(list_a) - 1:
print item, "is the last"
else:
print item, "is not the last"
结果:
0 is not the last
1 is not the last
3 is not the last
1 is the last