美文网首页Pythoner集中营程序员Python
python列表(list)中的del,remove,和pop的

python列表(list)中的del,remove,和pop的

作者: 老鼠慎言 | 来源:发表于2018-08-25 20:32 被阅读25次

先谈pop和remove

a = [1,2,3,4]

\color{red}{pop}

pop 接受的是元素的下标,在原列表中弹出这个元素,并返回
也就是说:

test_one = a.pop(1)

结果为:

test_one = 2
a = [1,3,4]

\color{red}{remove}

remove接受的是列表中的数,在原列表从左到右删除第一次出现的这个数,返回值为None
也就是说:

a=[1,2,1,3]
test_one = a.remove(1)

结果为:

test_one = None
a = [2,1,3]

\color{red}{del}

a=[1,2,1,3]
del a[1]

结果为:

a = [1,1,3]                                                                 
  • del 是一个语句,它直接销毁a[1]这个对象
  • del可以作用在任何对象上,不单单是列表里的某一个元素,比如del a,那么a这个列表就没有了
  • del 的速度更快,原因如下
在使用del时:python的内部调用是直接调用字节码,因为它是一个语句
del字节码.png

而使用remove,或者pop时,调用的是函数

remove字节码.png

调用字节码的时间肯定比调用函数的快

总结:\color{red}{remove}\color{red}{pop} 视情况使用,\color{red}{del}操作要比前两个快

相关文章

网友评论

    本文标题:python列表(list)中的del,remove,和pop的

    本文链接:https://www.haomeiwen.com/subject/abngiftx.html