3 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
some_list[-1]
some_list[-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[-1]
some_list

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果你str()或list()對(duì)象最終可能是空的:astr = ''或alist = [],那么您可能需要使用alist[-1:]而不是alist[-1]表示對(duì)象的“同一性”。
這一點(diǎn)的意義是:
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
其中的區(qū)別是返回空列表對(duì)象或空str對(duì)象更像是“最后一個(gè)元素”-就像一個(gè)異常對(duì)象。

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
>>> list[-1:] # returns indexed value [3]>>> list[-1] # returns value 3
添加回答
舉報(bào)