python pop()和remove()

来源:互联网 发布:linux 查看包依赖 编辑:程序博客网 时间:2024/06/05 16:30

http://www.cnblogs.com/sunxiaotao/p/4462347.html


Python关于删除list中的某个元素,一般有两种方法,pop()和remove()。

如果删除单个元素,使用基本没有什么问题,具体如下。

1.pop()方法,传递的是待删除元素的index:

1
2
3
4
5
6
7
= ['a''b''c''d']
x.pop(2)
print x
 
------------------
result:
['a''b''d']

  

2. remove()传递待删除元素,如果多个元素一样,默认删除第一个:

1
2
3
4
5
6
7
= ['a''b''a''c''d']
x.remove('a')
print x
 
-----------------
result:
['b''a''c''d']

  

如果要循环删除符合某个条件的元素,慎用!!

1
2
3
4
5
6
7
8
9
10
= ['a''b''c''d']
= ['b''c']
for in x:
    if in y:
        x.remove(i)
print x
 
-----------------------
result:
['a''c''d']

  

1
2
3
4
5
6
7
8
9
10
11
= ['a''b''c''d']
= ['b''c']
for in x:
    if in y:
        idx = x.index(i)
        x.pop(idx)
print x
 
--------------
result:
['a''c''d']

  我认为出现这种情况的主要原因是,pop和remove方法属于‘破坏性操作‘(ps:原谅我自创的定义),x.remove()后,内存中原来存放x的位置已经释放,又重新申请了内存存放新的x。可以理解为x已经不是原来的x了,而for循环中传递的x还是原来x在内存中的位置,所以在x.remove(i)后,for循环找不到x了,后面的删除即无法完成。为了完成循环删除list元素的问题,我推荐用下面的方法。

1
2
3
4
5
6
7
8
9
10
11
12
= ['a''b''c''d']
= ['b''c']
x_new = []
for in x:
    if not in y:
        x_new.append(i)
= x_new
print x
 
----------------------
result:
['a''d']

0 0
原创粉丝点击