簡體   English   中英

如何獲取列表的最后一個元素?

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

如何獲取列表的最后一個元素?

首選哪種方式?

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

some_list[-1]是最短和最 Pythonic 的。

事實上,你可以用這種語法做更多的事情。 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]將引發異常,因為空列表不能有最后一個元素。

如果您的str()list()對象可能最終為空: astr = ''alist = [] ,那么您可能希望使用alist[-1:]而不是alist[-1] for object "同一性”。

這樣做的意義在於:

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 對象更像是“最后一個元素”,然后是異常對象。

你也可以這樣做:

last_elem = alist.pop()

這取決於您想對列表做什么,因為pop()方法將刪除最后一個元素。

在 python 中顯示最后一個元素的最簡單方法是

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

還有許多其他方法可以實現這樣的目標,但這些方法都很簡短且易於使用。

在 Python 中,如何獲取列表的最后一個元素?

要獲取最后一個元素,

  • 不修改列表,並且
  • 假設您知道列表最后一個元素(即它是非空的)

-1傳遞給下標符號:

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

解釋

索引和切片可以將負整數作為參數。

我修改了文檔中的一個示例,以指示每個索引引用的序列中的哪個項目,在這種情況下,在字符串"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'

通過可迭代解包分配

為了獲取最后一個元素,此方法可能不必要地實現第二個列表,但為了完整性(並且因為它支持任何可迭代的 - 不僅僅是列表):

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

變量名,head 綁定到不必要的新創建列表:

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

如果您不打算對該列表執行任何操作,則更合適:

*_, last = a_list

或者,真的,如果你知道它是一個列表(或者至少接受下標符號):

last = a_list[-1]

在一個函數中

一位評論者說:

我希望 Python 有一個像 Lisp 一樣的 first() 和 last() 函數……它會擺脫很多不必要的 lambda 函數。

這些將很容易定義:

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

def first(a_list):
    return a_list[0]

或使用operator.itemgetter

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

在任一情況下:

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

特別案例

如果您正在做一些更復雜的事情,您可能會發現以稍微不同的方式獲取最后一個元素會更高效。

如果您不熟悉編程,則應避免使用此部分,因為它將算法的其他語義不同部分耦合在一起。 如果你在一個地方改變你的算法,它可能會對另一行代碼產生意想不到的影響。

我嘗試盡可能完整地提供警告和條件,但我可能遺漏了一些東西。 如果您認為我留下警告,請發表評論。

切片

列表的切片返回一個新列表 - 因此,如果我們想要新列表中的元素,我們可以從 -1 切片到末尾:

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

如果列表為空,這樣做的好處是不會失敗:

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

而嘗試通過索引訪問會引發IndexError需要處理:

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

但同樣,只有在需要時才應為此目的進行切片:

  • 創建了一個新列表
  • 如果先前的列表為空,則新列表為空。

for循環

作為 Python 的一個特性, for循環中沒有內部作用域。

如果您已經對列表執行了完整的迭代,最后一個元素仍將被循環中分配的變量名引用:

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

這在語義上不是列表中的最后一件事。 從語義上講,這是名稱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'

因此,這應該只用於獲取最后一個元素,如果你

  • 已經在循環,並且
  • 您知道循環將完成(不會因錯誤而中斷或退出),否則它將指向循環引用的最后一個元素。

獲取和刪除它

我們還可以通過刪除並返回最后一個元素來改變我們的原始列表:

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

但是現在原始列表被修改了。

-1實際上是默認參數,因此list.pop可以在沒有索引參數的情況下使用):

>>> a_list.pop()
'two'

僅在以下情況下執行此操作

  • 您知道列表中有元素,或者如果它為空,則准備處理異常,並且
  • 您確實打算從列表中刪除最后一個元素,將其視為堆棧。

這些是有效的用例,但不是很常見。

將其余部分保存以備后用:

我不知道你為什么要這樣做,但為了完整起見,由於reversed返回一個迭代器(它支持迭代器協議),你可以將其結果傳遞給next

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

所以這就像做這個的相反:

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

但是我想不出這樣做的充分理由,除非您稍后需要反向迭代器的其余部分,它可能看起來更像這樣:

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

use_later = list(reverse_iterator)

現在:

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

要防止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'

另一種方法:

some_list.reverse() 
some_list[0]

lst[-1]是最好的方法,但是對於一般的可迭代對象,請考慮more_itertools.last

代碼

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]將檢索列表的最后一個元素而不更改列表。 list.pop()將檢索列表的最后一個元素,但它會改變/更改原始列表。 通常,不建議更改原始列表。

或者,如果由於某種原因,您正在尋找不那么 Python 的東西,您可以使用list[len(list)-1] ,假設列表不為空。

如果您不想在列表為空時獲取 IndexError,也可以使用下面的代碼。

next(reversed(some_list), None)

好的,但是在幾乎所有語言方式中都很常見items[len(items) - 1]呢? 這是 IMO 獲取最后一個元素的最簡單方法,因為它不需要任何Python知識。

這是您查詢的解決方案。

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.

輸出:

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

奇怪的是還沒有人發布這個:

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

解包就行了。

蟒蛇方式

所以讓我們考慮一下我們有一個列表a = [1,2,3,4] ,在 Python 中可以操作 List 來給我們它的一部分或它的一個元素,使用下面的命令可以很容易地得到最后一個元素。

print(a[-1])

在 Python 中訪問列表中的最后一個元素:

1:使用負索引訪問最后一個元素 -1

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

2. 使用 pop() 方法訪問最后一個元素

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

但是,pop 方法將從列表中刪除最后一個元素。

為避免“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))

您還可以使用長度來獲取最后一個元素:

last_elem = arr[len(arr) - 1]

如果列表為空,您將得到一個IndexError異常,但您也可以通過arr[-1]得到它。

以下是如果列表為空時不需要IndexError的代碼。 next(reversed(some_list), None)

如果你這樣做my_list[-1]這將返回列表的最后一個元素。 負序列索引表示從數組末尾開始的位置。 負索引表示從末尾開始,-1 指最后一項,-2 指倒數第二項,依此類推。

您只需要獲取並放置 [-1] 索引。 例如:

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

您將得到 2 作為輸出。

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

另一個簡單的解決方案

找不到任何提到這一點的答案。 所以補充。

您也可以嘗試some_list[~0]

那是波浪號

您可以將其與nextiter[::-1]一起使用:

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

如果您使用負數,它將開始為您提供最后一個元素,如果列表示例

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

結果

9

您可以使用~運算符從 end 獲取第 i 個元素(從 0 開始索引)。

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

Python 中的列表是什么?

該列表是 Python 中最常用的數據類型之一。 列表是可以是任何數據類型的元素的集合。 單個列表可以包含數字、字符串、嵌套列表等的組合。

如何獲取 Python 中列表的最后一個元素


方法 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

方法 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

方法 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

方法 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

方法 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

在此處輸入圖像描述

方法一:

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

方法二:

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

方法3:

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

方法四:

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

方法5:

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

全部輸出 78

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM