简体   繁体   English

在Python中访问列表中的最后一个元素

[英]Accessing the last element in a list in Python

I have a list for example: list_a = [0,1,3,1] 我有一个列表例如:list_a = [0,1,3,1]

and I am trying to iterate through each number this loop, and if it hits the last "1" in the list, print "this is the last number in the list" 我试图遍历每个数字这个循环,如果它击中列表中的最后一个“1”,打印“这是列表中的最后一个数字”

since there are two 1's, what is a way to access the last 1 in the list? 既然有两个1,那么访问列表中最后1个的方法是什么?

I tried: 我试过了:

 if list_a[-1] == 1:
      print "this is the last"  
   else:
     # not the last

This does not work since the second element is also a 1. Tried: 这不起作用,因为第二个元素也是1.尝试:

if list_a.index(3) == list_a[i] is True:
   print "this is the last"

also did not work, since there are two 1's 也没用,因为有两个1

list_a[-1]是访问最后一个元素的方法

You can use enumerate to iterate through both the items in the list, and the indices of those items. 您可以使用枚举来遍历列表中的项目以及这些项目的索引。

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"

Result: 结果:

0 is not the last
1 is not the last
3 is not the last
1 is the last

Tested on Python 2.7.3 在Python 2.7.3上测试

This solution will work for any sized list. 此解决方案适用于任何大小的列表。

list_a = [0,1,3,1]

^ We define list_a 我们定义list_a

last = (len(list_a) - 1)

^We count the number of elements in the list and subtract 1. This is the coordinate of the last element. ^我们计算列表中元素的数量并减去1.这是最后一个元素的坐标。

print "The last variable in this list is", list_a[last]

^We display the information. 我们显示信息。

a = [1, 2, 3, 4, 1, 'not a number']
index_of_last_number = 0

for index, item in enumerate(a):
    if type(item) == type(2):
        index_of_last_number = index

The output is 4, the index in array a of the last integer. 输出为4,索引在最后一个整数的数组a中。 If you want to include types other than integers, you can change the type(2) to type(2.2) or something. 如果要包括整数以外的类型,可以将类型(2)更改为类型(2.2)或其他类型。

To be absolutely sure you find the last instance of "1" you have to look at all the items in the list. 要确保您找到最后一个“1”实例,您必须查看列表中的所有项目。 There is a possibility that the last "1" will not be the last item in the list. 最后一个“1”可能不是列表中的最后一项。 So, you have to look through the list, and remember the index of the last one found, then you can use this index. 因此,您必须查看列表,并记住找到的最后一个索引,然后您可以使用此索引。

list_a = [2, 1, 3, 4, 1, 5, 6]

lastIndex = 0

for index, item in enumerate(list_a):
    if item == 1:
        lastIndex = index

print lastIndex

output: 输出:

4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM