简体   繁体   English

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

[英]How do I get the last element of a list?

How do I get the last element of a list?如何获取列表的最后一个元素?

Which way is preferred?首选哪种方式?

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

some_list[-1] is the shortest and most Pythonic. some_list[-1]是最短和最 Pythonic 的。

In fact, you can do much more with this syntax.事实上,你可以用这种语法做更多的事情。 The some_list[-n] syntax gets the nth-to-last element. some_list[-n]语法获取倒数第 n 个元素。 So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)] , which gives you the first element.所以some_list[-1]得到最后一个元素, some_list[-2]得到倒数第二个,等等,一直到some_list[-len(some_list)] ,它给你第一个元素。

You can also set list elements in this way.您也可以通过这种方式设置列表元素。 For instance:例如:

>>> 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]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist.请注意,如果预期的项目不存在,按索引获取列表项将引发IndexError This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.这意味着如果some_list为空, some_list[-1]将引发异常,因为空列表不能有最后一个元素。

If your str() or list() objects might end up being empty as so: astr = '' or alist = [] , then you might want to use alist[-1:] instead of alist[-1] for object "sameness".如果您的str()list()对象可能最终为空: astr = ''alist = [] ,那么您可能希望使用alist[-1:]而不是alist[-1] for object "同一性”。

The significance of this is:这样做的意义在于:

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

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.区别在于返回空列表对象或空 str 对象更像是“最后一个元素”,然后是异常对象。

You can also do:你也可以这样做:

last_elem = alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。

The simplest way to display last element in python is在 python 中显示最后一个元素的最简单方法是

>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

there are many other method to achieve such a goal but these are short and sweet to use.还有许多其他方法可以实现这样的目标,但这些方法都很简短且易于使用。

In Python, how do you get the last element of a list?在 Python 中,如何获取列表的最后一个元素?

To just get the last element,要获取最后一个元素,

  • without modifying the list, and不修改列表,并且
  • assuming you know the list has a last element (ie it is nonempty)假设您知道列表最后一个元素(即它是非空的)

pass -1 to the subscript notation:-1传递给下标符号:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation解释

Indexes and slices can take negative integers as arguments.索引和切片可以将负整数作为参数。

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python" , -1 references the last element, the character, 'n' :我修改了文档中的一个示例,以指示每个索引引用的序列中的哪个项目,在这种情况下,在字符串"Python"中, -1引用最后一个元素,字符, 'n'

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking通过可迭代解包分配

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):为了获取最后一个元素,此方法可能不必要地实现第二个列表,但为了完整性(并且因为它支持任何可迭代的 - 不仅仅是列表):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:变量名,head 绑定到不必要的新创建列表:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:如果您不打算对该列表执行任何操作,则更合适:

*_, last = a_list

Or, really, if you know it's a list (or at least accepts subscript notation):或者,真的,如果你知道它是一个列表(或者至少接受下标符号):

last = a_list[-1]

In a function在一个函数中

A commenter said:一位评论者说:

I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.我希望 Python 有一个像 Lisp 一样的 first() 和 last() 函数……它会摆脱很多不必要的 lambda 函数。

These would be quite simple to define:这些将很容易定义:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter :或使用operator.itemgetter

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:在任一情况下:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases特别案例

If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.如果您正在做一些更复杂的事情,您可能会发现以稍微不同的方式获取最后一个元素会更高效。

If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together.如果您不熟悉编程,则应避免使用此部分,因为它将算法的其他语义不同部分耦合在一起。 If you change your algorithm in one place, it may have an unintended impact on another line of code.如果你在一个地方改变你的算法,它可能会对另一行代码产生意想不到的影响。

I try to provide caveats and conditions as completely as I can, but I may have missed something.我尝试尽可能完整地提供警告和条件,但我可能遗漏了一些东西。 Please comment if you think I'm leaving a caveat out.如果您认为我留下警告,请发表评论。

Slicing切片

A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:列表的切片返回一个新列表 - 因此,如果我们想要新列表中的元素,我们可以从 -1 切片到末尾:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:如果列表为空,这样做的好处是不会失败:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:而尝试通过索引访问会引发IndexError需要处理:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:但同样,只有在需要时才应为此目的进行切片:

  • a new list created创建了一个新列表
  • and the new list to be empty if the prior list was empty.如果先前的列表为空,则新列表为空。

for loops for循环

As a feature of Python, there is no inner scoping in a for loop.作为 Python 的一个特性, for循环中没有内部作用域。

If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:如果您已经对列表执行了完整的迭代,最后一个元素仍将被循环中分配的变量名引用:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list.这在语义上不是列表中的最后一件事。 This is semantically the last thing that the name, item , was bound to.从语义上讲,这是名称item绑定的最后一件事。

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you因此,这应该只用于获取最后一个元素,如果你

  • are already looping, and已经在循环,并且
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.您知道循环将完成(不会因错误而中断或退出),否则它将指向循环引用的最后一个元素。

Getting and removing it获取和删除它

We can also mutate our original list by removing and returning the last element:我们还可以通过删除并返回最后一个元素来改变我们的原始列表:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.但是现在原始列表被修改了。

( -1 is actually the default argument, so list.pop can be used without an index argument): -1实际上是默认参数,因此list.pop可以在没有索引参数的情况下使用):

>>> a_list.pop()
'two'

Only do this if仅在以下情况下执行此操作

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and您知道列表中有元素,或者如果它为空,则准备处理异常,并且
  • you do intend to remove the last element from the list, treating it like a stack.您确实打算从列表中删除最后一个元素,将其视为堆栈。

These are valid use-cases, but not very common.这些是有效的用例,但不是很常见。

Saving the rest of the reverse for later:将其余部分保存以备后用:

I don't know why you'd do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next :我不知道你为什么要这样做,但为了完整起见,由于reversed返回一个迭代器(它支持迭代器协议),你可以将其结果传递给next

>>> next(reversed([1,2,3]))
3

So it's like doing the reverse of this:所以这就像做这个的相反:

>>> next(iter([1,2,3]))
1

But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:但是我想不出这样做的充分理由,除非您稍后需要反向迭代器的其余部分,它可能看起来更像这样:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:现在:

>>> use_later
[2, 1]
>>> last_element
3

To prevent IndexError: list index out of range , use this syntax:要防止IndexError: list index out of range ,请使用以下语法:

mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

Another method:另一种方法:

some_list.reverse() 
some_list[0]

lst[-1] is the best approach, but with general iterables, consider more_itertools.last : lst[-1]是最好的方法,但是对于一般的可迭代对象,请考虑more_itertools.last

Code代码

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

list[-1] will retrieve the last element of the list without changing the list. list[-1]将检索列表的最后一个元素而不更改列表。 list.pop() will retrieve the last element of the list, but it will mutate/change the original list. list.pop()将检索列表的最后一个元素,但它会改变/更改原始列表。 Usually, mutating the original list is not recommended.通常,不建议更改原始列表。

Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1] , assuming the list is not empty.或者,如果由于某种原因,您正在寻找不那么 Python 的东西,您可以使用list[len(list)-1] ,假设列表不为空。

如果您不想在列表为空时获取 IndexError,也可以使用下面的代码。

next(reversed(some_list), None)

Ok, but what about common in almost every language way items[len(items) - 1] ?好的,但是在几乎所有语言方式中都很常见items[len(items) - 1]呢? This is IMO the easiest way to get last element, because it does not require anything pythonic knowledge.这是 IMO 获取最后一个元素的最简单方法,因为它不需要任何Python知识。

Here is the solution for your query.这是您查询的解决方案。

a=["first","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the last second item in the list.

Output:输出:

>>> first
>>> last
>>> second from last

Strange that nobody posted this yet:奇怪的是还没有人发布这个:

>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>> 

Just unpack.解包就行了。

Pythonic Way蟒蛇方式

So lets consider that we have a list a = [1,2,3,4] , in Python List can be manipulated to give us part of it or a element of it, using the following command one can easily get the last element.所以让我们考虑一下我们有一个列表a = [1,2,3,4] ,在 Python 中可以操作 List 来给我们它的一部分或它的一个元素,使用下面的命令可以很容易地得到最后一个元素。

print(a[-1])

Accessing the last element from the list in Python:在 Python 中访问列表中的最后一个元素:

1: Access the last element with negative indexing -1 1:使用负索引访问最后一个元素 -1

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data[-1]
'w'

2. Access the last element with pop() method 2. 使用 pop() 方法访问最后一个元素

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data.pop()
'w'

However, pop method will remove the last element from the list.但是,pop 方法将从列表中删除最后一个元素。

To avoid "IndexError: list index out of range", you can use this piece of code.为避免“IndexError: list index out of range”,您可以使用这段代码。

list_values = [12, 112, 443]

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

print(getLastElement(list_values))

You can also use the length to get the last element:您还可以使用长度来获取最后一个元素:

last_elem = arr[len(arr) - 1]

If the list is empty, you'll get an IndexError exception, but you also get that with arr[-1] .如果列表为空,您将得到一个IndexError异常,但您也可以通过arr[-1]得到它。

the below is the code if IndexError is not needed when list is empty. 以下是如果列表为空时不需要IndexError的代码。 next(reversed(some_list), None)

If you do my_list[-1] this returns the last element of the list.如果你这样做my_list[-1]这将返回列表的最后一个元素。 Negative sequence indexes represent positions from the end of the array.负序列索引表示从数组末尾开始的位置。 Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.负索引表示从末尾开始,-1 指最后一项,-2 指倒数第二项,依此类推。

You will just need to take the and put [-1] index.您只需要获取并放置 [-1] 索引。 For example:例如:

list=[0,1,2]
last_index=list[-1]
print(last_index)

You will get 2 as the output.您将得到 2 作为输出。

array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

Another simple solution另一个简单的解决方案

Couldn't find any answer mentioning this.找不到任何提到这一点的答案。 So adding.所以补充。

You could try some_list[~0] also.您也可以尝试some_list[~0]

That's the tilde symbol那是波浪号

You could use it with next and iter with [::-1] :您可以将其与nextiter[::-1]一起使用:

>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>> 

If you use negative numbers, it will start giving you elements from last if the list Example如果您使用负数,它将开始为您提供最后一个元素,如果列表示例

lst=[1,3,5,7,9]
print(lst[-1])

Result结果

9

You can use ~ operator to get the ith element from end (indexed from 0).您可以使用~运算符从 end 获取第 i 个元素(从 0 开始索引)。

lst=[1,3,5,7,9]
print(lst[~0])

What is a List in Python? Python 中的列表是什么?

The list is one of the most commonly used data types in Python.该列表是 Python 中最常用的数据类型之一。 A list is a collection of elements that can be of any data type.列表是可以是任何数据类型的元素的集合。 A single list can contain a combination of numbers, strings, nested lists, etc.单个列表可以包含数字、字符串、嵌套列表等的组合。

How to Get the Last Element of a List in Python如何获取 Python 中列表的最后一个元素


Method 1 – By Iterating all the elements in a list方法 1 – 通过迭代列表中的所有元素

numbers_list = [1, 2, 3, 4, 5, 6, 7]

# using loop method to print last element 
for i in range(0, len(number_list)):
  
    if i == (len(number_list)-1):
        print ("The last element of list is : ", number_list[i])

# Output
The last element of list is : 7

Method 2 – Using the reverse() method方法 2 – 使用reverse()方法

numbers_list = [1, 2, 3, 4, 5, 6, 7]

# using reverse method to print last element
number_list.reverse()
print("The last element of list using reverse method are :", number_list[0])

# Output
The last element of list using reverse method are : 7

Method 3 – Using pop() method方法 3 – 使用pop()方法

numbers_list = [1, 2, 3, 4, 5, 6, 7]

# using pop()  method to print last element
print("The last element of list using reverse method are :", number_list.pop())

# Output
The last element of list using reverse method are : 7

Method 4 – Using Negative Indexing [] Operator方法 4 – 使用负索引[]运算符

numbers_list = [1, 2, 3, 4, 5, 6, 7]

# using length-1 to print last element
print("The last element of list using length-1 method are :", number_list[len(number_list) -1])

# using [] operator to print last element
print("The last element of list using reverse method are :", number_list[-1])

# Output
The last element of list using length-1 method are : 7
The last element of list using reverse method are : 7

Method 5 – Using itemgetter()方法 5 – 使用itemgetter()

import operator

numbers_list = [1, 2, 3, 4, 5, 6, 7]

getLastElement = operator.itemgetter(-1)


# using [] operator to print last element
print("The last element of list using reverse method are :", getLastElement(number_list))

# Output
The last element of list using reverse method are : 7

在此处输入图像描述

METHOD 1:方法一:

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

METHOD 2:方法二:

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

METHOD 3:方法3:

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

METHOD 4:方法四:

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

METHOD 5:方法5:

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

All are outputting 78全部输出 78

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

相关问题 如何计算某个元素之后列表中的最后一个元素? - How do I count the last elements in a list after a certain element? 如何删除列表中元素的最后2个字符? - How do I remove the last 2 characters of an element in a list? 如何获取元素所在的列表? - How do I get the list in which an element is in? 如何获取列表中的第二个元素并将 append 获取到不同的列表 - How do I get a second element in a list and append it to different list 如何获取JSON列表的最后一个元素 - How to get last element of a JSON list 如何在链表中递归查找元素,但最后一个元素不等于None - how do I recursively find an element in a linked list but the last element is not equal to None 如何将列表中的最后一个元素移动到 python 中列表的第三个 position? - How do I move my last element in the list to the 3rd position of the list in python? 如何从列表中的索引 1 开始并在列表中的最后一个元素之前结束 - How do I start at index 1 in my list and end just before the last element in the list 如何使输出的最后一列仅包含列表的每个元素而不是整个列表? - How do I make the last column of my output include only each element of the list instead of the whole list? 如何获取列表的第 n 个元素并与同一列表的最后 n 个元素进行比较 - How do I take the nth element of a list and compare to the last nth elements of the same list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM