列表1的引用索引

2024-04-20 13:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么不打印列表中的最后一个元素。你知道吗

>>> a_lst = [1,2,3,4,5,6]
>>> print a_lst[-1]
6
>>> print a_lst[0:-1]
[1, 2, 3, 4, 5]

我可以看到,如果我只执行一个\u lst[-1],它将返回预期的最后一个元素。但是当我尝试在[0:-1]范围内使用它时,它实际上返回倒数第二个元素?你知道吗


Tags: 元素列表printlst倒数
1条回答
网友
1楼 · 发布于 2024-04-20 13:35:55

a_lst[0:-1]这取决于但不包括最后一个元素,a_lst[-1]只是最后一个元素。你知道吗

a_lst[0:]将获得所有元素。你知道吗

当你切片一个列表时,它会进入a_list[start:stop-1:step],这一步是可选的

In [32]: l[0:-1]
Out[32]: [1, 2, 3, 4, 5]  # all but last element

In [33]: l[0::2]  # start at first and step of 2
Out[33]: [1, 3, 5]

In [34]: l[0::3]  # start at first and step of 3
Out[34]: [1, 4]

相关问题 更多 >