對python中數(shù)組的del,remove,pop區(qū)別詳解
以a=[1,2,3] 為例,似乎使用del, remove, pop一個元素2 之后 a都是為 [1,3],
如下:
>>> a=[1,2,3] >>> a.remove(2) >>> a [1, 3] >>> a=[1,2,3] >>> del a[1] >>> a [1, 3] >>> a= [1,2,3] >>> a.pop(1) 2 >>> a [1, 3] >>>
那么Python對于列表的del, remove, pop操作,它們之間有何區(qū)別呢?
首先,remove 是刪除首個符合條件的元素。并不是刪除特定的索引。
如下例:
>>> a = [0, 2, 2, 3] >>> a.remove(2) >>> a [0, 2, 3]
而對于 del 來說,它是根據(jù)索引(元素所在位置)來刪除的,如下例:
>>> a = [3, 2, 2, 1] >>> del a[1] [3, 2, 1]
第1個元素為a[0] --是以0開始計數(shù)的。則a[1]是指第2個元素,即里面的值2.
最后我們再看看pop
>>> a = [4, 3, 5] >>> a.pop(1) 3 >>> a [4, 5]
pop返回的是你彈出的那個數(shù)值。
所以使用時要根據(jù)你的具體需求選用合適的方法。
另外它們?nèi)绻鲥e,出錯模式也是不一樣的。
注意看下面區(qū)別:
>>> a = [4, 5, 6] >>> a.remove(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list >>> del a[7] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range >>> a.pop(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop index out of range
以上這篇對python中數(shù)組的del,remove,pop區(qū)別詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Python實(shí)現(xiàn)蒙特卡洛法計算圓周率π
蒙特卡羅法也稱統(tǒng)計模擬法、統(tǒng)計試驗法,是把概率現(xiàn)象作為研究對象的數(shù)值模擬方法,是按抽樣調(diào)查法求取統(tǒng)計值來推定未知特性量的計算方法,本文我們將介紹如何使用Python來實(shí)現(xiàn)蒙特卡洛法計算圓周率π,感興趣的朋友可以參考下2023-06-06wxPython中l(wèi)istbox用法實(shí)例詳解
這篇文章主要介紹了wxPython中l(wèi)istbox用法,以實(shí)例形式較為詳細(xì)的分析了Python使用wxPython中l(wèi)istbox的相關(guān)技巧,需要的朋友可以參考下2015-06-06Python的getattr函數(shù)方法學(xué)習(xí)使用示例
這篇文章主要為大家介紹了Python的getattr方法學(xué)習(xí)使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08python3.4用函數(shù)操作mysql5.7數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了python3.4用函數(shù)操作mysql5.7數(shù)據(jù)庫,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06