3 回答

TA貢獻1895條經驗 獲得超3個贊
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貢獻1873條經驗 獲得超9個贊
如果你str()或list()對象最終可能是空的:astr = ''或alist = [],那么您可能需要使用alist[-1:]而不是alist[-1]表示對象的“同一性”。
這一點的意義是:
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對象更像是“最后一個元素”-就像一個異常對象。

TA貢獻1845條經驗 獲得超8個贊
>>> list[-1:] # returns indexed value [3]>>> list[-1] # returns value 3
添加回答
舉報