串列基本上是 Python 中最常用的資料結構之一了,并且洗掉操作也是經常使用的,
那到底有哪些方法可以洗掉串列中的元素呢?這篇文章就來總結一下,
一共有三種方法,分別是 remove,pop 和 del,下面來詳細說明,
remove
L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present.
remove 是從串列中洗掉指定的元素,引數是 value,
舉個例子:
>>> lst = [1, 2, 3]
>>> lst.remove(2)
>>> lst
[1, 3]
需要注意,remove 方法沒有回傳值,而且如果洗掉的元素不在串列中的話,會發生報錯,
>>> lst = [1, 2, 3]
>>> lst.remove(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
pop
L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range.
pop 是洗掉指定索引位置的元素,引數是 index,如果不指定索引,默認洗掉串列最后一個元素,
>>> lst = [1, 2, 3]
>>> lst.pop(1)
2
>>> lst
[1, 3]
>>>
>>>
>>>
>>> lst = [1, 2, 3]
>>>
>>> lst.pop()
3
pop 方法是有回傳值的,如果洗掉索引超出串列范圍也會報錯,
>>> lst = [1, 2, 3]
>>> lst.pop(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>>
del
del 一般用在字典比較多,不過也可以用在串列上,
>>> lst = [1, 2, 3]
>>> del(lst[1])
>>> lst
[1, 3]
直接傳元素值是不行的,會報錯:
>>> lst = [1, 2, 3]
>>> del(2)
File "<stdin>", line 1
SyntaxError: cannot delete literal
del 還可以洗掉整個串列:
>>> lst = [1, 2, 3]
>>> del(lst)
>>>
>>> lst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lst' is not defined
以上就是本文的全部內容,如果覺得還不錯的話,歡迎點贊,轉發和關注,感謝支持,
推薦閱讀:
- 計算機經典書籍
- 技術博客: 硬核后端開發技術干貨,內容包括 Python、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等,
- Go 程式員: Go 學習路線圖,包括基礎專欄,進階專欄,原始碼閱讀,實戰開發,面試刷題,必讀書單等一系列資源,
- 面試題匯總: 包括 Python、Go、Redis、MySQL、Kafka、資料結構、演算法、編程、網路等各種常考題,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459513.html
標籤:Python
上一篇:python輸入和輸出
