Home >Backend Development >Python Tutorial >python删除列表内容

python删除列表内容

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-10 15:08:151398browse

今天有点囧

a=['XXXX_game.sql', 'XXXX_game_sp.sql', 'XXXX_gamelog_sp.sql', 'XXXX_gamelog.sql']
for i in a:
  if 'gamelog' in i:
    a.remove(i)
print a
['XXXX_game.sql', 'XXXX_game_sp.sql', 'XXXX_gamelog.sql']

历遍的过程中明显MISS掉了   'XXXX_gamelog.sql'  这个项目,大家可以自己试试,为什么会没删完,这到底是什么原因呢?

我们再验证一次

for i in a:
  if 'gamelog' in i:
    print i,
 
XXXX_gamelog_sp.sql XXXX_gamelog.sql

看到结果,如果我们不对它进行remove的操作,是不会有问题的。完全可以历遍。

这样我们大概知道了,在对列表进行remove操作的时候,用历遍的方法是不行的。那如何解决?

a1=a[::]      #这里我们镜像一个列表a1,但是千万别用a1=a,为什么,我们可以测试下 a1=a[::] a1==a True; a1 is a False; 如果用a1=a a1==a True; a1 is a True,下来大家可以测试下,这个是列表的一个特性。
for i in a1:
  if 'gamelog' in i:
    a.remove(i)
print a
 
['XXXX_game.sql', 'XXXX_game_sp.sql']

再来一个例子

[ { 'Num': '001', 'Name': '张三', 'Workingtime': 'Monday', 'Money': '100' }
 { 'Num': '002', 'Name': '李四', 'Workingtime': 'Tuesday', 'Money': '200' }]
因为有'张三',所以删除 { 'Num': '001', 'Name': '张三', 'Workingtime': 'Monday', 'Money': '100'}整一行,怎么操作

思路是找到要删除的元素在列表中的索引,然后调用 pop,索引作为参数。pop 返回被删除的元素。队列剩下的就是删除该索引元素之后的剩余的。

lname = [ { 'Num': '001', 'Name': '张三', 'Workingtime': 'Monday', 'Money': '100' } { 'Num': '002', 'Name': '李四', 'Workingtime': 'Tuesday', 'Money': '200' }]
for x in range(len(lname)):  #列表遍历  
    if l[x]['name'] == u'张三':    
    lname.pop(x)      #用 pop。
    break         #操作完成,break 出去

好了,今天就先到这里

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn