
在Python中,我們可以使用索引
-1
來擷取清單的最後一個元素。
#!/usr/bin/python
nums = [1, 2, 3, 4, 5]
print(nums[-1])
print(nums[-2])
print(nums[-3])
print(nums[-4])
print(nums[-5])
print(nums[0])
print(nums[1])
print(nums[2])
print(nums[3])
print(nums[4])
輸出量
5
4
3
2
1
1
2
3
4
5
又一個例子
#!/usr/bin/python
# getting list of nums from the user
nums = list(map(int, input("Enter space separated numbers").split()))
# accessing the last element using -1 index
print(nums[-1])
輸出量
Enter space separated numbers 1 2 3 4 5
5
參考文獻:
Pyhton doc資料結構
翻譯自: https://mkyong.com/python/python-get-the-last-element-of-a-list/
推薦閱讀--
Python 隻用一行代碼,可以實作哪些事兒?
當pandas撞上了sql,于是一個強大的pandasql庫産生了!
牛了!Python最容易入的10個坑!