如何获取列表的最后一个元素?

首选哪种方式?

alist[-1]
alist[len(alist) - 1]

当前回答

如果str()或list()对象最终可能为空:astr=“”或alist=[],那么您可能希望使用alist[-1:]而不是alist[-1]来表示对象“sameness”。

其意义在于:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

区别在于,返回空列表对象或空str对象更像是“最后一个元素”,而不是异常对象。

其他回答

方法1:

L = [8, 23, 45, 12, 78]
print(L[len(L)-1])

方法2:

L = [8, 23, 45, 12, 78]
print(L[-1])

方法3:

L = [8, 23, 45, 12, 78]
L.reverse() 
print(L[0])

方法4:

L = [8, 23, 45, 12, 78]
print(L[~0])

方法5:

L = [8, 23, 45, 12, 78]
print(L.pop())

全部输出78

为了避免“IndexError:列表索引超出范围”,可以使用这段代码。

list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))

some_list[-1]是最短、最Python的。

事实上,使用这种语法可以做得更多。some_list[-n]语法获取倒数第n个元素。因此,some_list[-1]获取最后一个元素,some_list[-2]获取倒数第二个元素,等等,一直到some_list[-len(some_list)],这为您提供了第一个元素。

也可以用这种方式设置列表元素。例如:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

注意,如果期望的项不存在,则通过索引获取列表项将引发IndexError。这意味着如果some_list为空,some_list[-1]将引发异常,因为空列表不能有最后一个元素。

找不到任何提及此的答案。所以补充道。

您也可以尝试some_list[~0]。

那是波浪符号

另一种方法:

some_list.reverse() 
some_list[0]