共計 568 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Python 中,pop()
是一個列表(或其他類似容器)的方法,用于刪除并返回指定索引位置的元素。它的用法如下:
list.pop(index)
其中,list
是要操作的列表,index
是要刪除元素的索引位置。如果不提供索引參數(shù),則默認刪除并返回列表中的最后一個元素。
下面是一個例子來演示 pop()
的用法:
fruits = ['apple', 'banana', 'orange', 'grape']
# 刪除并返回索引為 1 的元素
removed_fruit = fruits.pop(1)
print(removed_fruit) # 輸出:'banana'
print(fruits) # 輸出:['apple', 'orange', 'grape']
# 刪除并返回最后一個元素
last_fruit = fruits.pop()
print(last_fruit) # 輸出:'grape'
print(fruits) # 輸出:['apple', 'orange']
需要注意的是,當(dāng)使用 pop()
方法時,被刪除的元素將不再在列表中存在。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完