pop()
方法是Python中的列表方法之一,用於刪除並返回列表中指定位置的元素,如果未指定位置,則默認為最後一個元素。這個方法可以大量簡化列表修改的代碼流程,提高代碼的可讀性和可維護性。
一、刪除並返回最後一個元素
在默認情況下,不填任何參數,列表將刪除並返回最後一個元素。這個方法可以用在需要刪除列表中最後一個元素的場景,比如取消訂單時需要刪除最後一項購物車中的物品。
cart = ['apple', 'banana', 'orange', 'watermelon']
last_item = cart.pop()
print(f'{last_item} has been removed from cart.')
print(f'The remaining items in the cart are {cart}.')
#輸出:watermelon has been removed from cart.
#The remaining items in the cart are ['apple', 'banana', 'orange']
二、刪除並返回指定位置的元素
除了刪除最後一個元素之外,在pop方法中還可以指定要刪除的元素的位置。將要刪除的元素的索引值作為pop方法的唯一參數,列表將執行剩餘部分的元素的“重排”操作,返回刪除的元素。
cart = ['apple', 'banana', 'orange', 'watermelon']
second_item = cart.pop(1)
print(f'{second_item} has been removed from cart.')
print(f'The remaining items in the cart are {cart}.')
#輸出:banana has been removed from cart.
#The remaining items in the cart are ['apple', 'orange', 'watermelon']
在上面的代碼中,pop方法的唯一參數是數字1,它表示要刪除的元素的索引位置為1。在執行此代碼之後,輸出將會顯示已經從列表中刪除了’banana’,剩下的元素重新排列,組成了[‘apple’, ‘orange’, ‘watermelon’]。
三、刪除列表中特定元素
除了按索引刪除元素之外,pop()
方法還可以通過指定元素值實現刪除。其步驟如下:
- 找到列表中需要刪除的元素
- 獲取該元素的索引值
- 用pop方法刪除該索引值的元素
下面是一段通過元素值刪除列表元素的代碼:
cart = ['apple', 'banana', 'orange', 'watermelon']
item = 'banana'
index = cart.index(item)
cart.pop(index)
print(f'The item {item} has been removed from the cart. The cart now contains: {cart}')
# 輸出:The item banana has been removed from the cart. The cart now contains: ['apple', 'orange', 'watermelon']
在上面的代碼中,我們使用列表的index()
方法找到了要刪除的元素’banana’在列表中的位置,然後使用pop方法刪除該位置的元素。最終輸出結果為:The item banana has been removed from the cart. The cart now contains: [‘apple’, ‘orange’, ‘watermelon’]。
四、給pop方法指定默認值
當嘗試刪除一個不存在於列表中的元素時,python解釋器會報錯。但是我們可以用pop()
方法的第二個參數,為它指定一個默認值,防止發生這種錯誤。
cart = ['apple', 'banana', 'orange', 'watermelon']
item = 'pear'
index = cart.index(item) if item in cart else None
if index is not None:
cart.pop(index)
print(f'The item {item} has been removed from the cart. The cart now contains: {cart}')
else:
default_item = cart.pop()
print(f'The item {item} is not in the cart, {default_item} has been removed from the cart. The cart now contains: {cart}')
# 輸出:The item pear is not in the cart, watermelon has been removed from the cart. The cart now contains: ['apple', 'banana', 'orange']
當刪除不存在於列表中的元素時,我們使用的是一個默認值,它可以從刪除的對象中轉移而來(當刪除列表中一個不存在的元素時,就會從列表的末尾刪除一個元素),用於在遇到問題時提供一些友好的反饋。
五、總結
pop()
方法可以用於刪除並返回列表中的元素。從指定位置刪除,刪除最後一個元素或通過元素的值刪除。在使用pop方法時,我們應該儘可能的使用默認參數,以在代碼中隱藏更多細節。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/296108.html