为什么我从列表开头删除偶数的代码不起作用? [英] Why does my code for removing the even numbers from the beginning of a list not work?

查看:52
本文介绍了为什么我从列表开头删除偶数的代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def delete_starting_evens(lst):
  for i in lst:
    if i%2==0:
      lst.remove(i)
    else:
      break
  return lst

给定的代码会产生意外的结果,但是我无法从输出中找出问题所在.

The given code produces unexpected results, but I'm not able to figure out from the output where the problem lies.

推荐答案

这是因为您要抑制for循环要迭代的列表项.因此,它抑制了一半的物品.例如,如果您在列表 [2、2、4、6、1] 上调用函数,它将删除列表的前2个,然后移至 lst [1] 它是4(删除前2个),然后删除它,然后移到现在是1并终止的 lst [2] .结果列表将为 [2,6,1]

That's because you're suppressing items of a list your for-loop is iterating on. Hence it suppresses half of your items. For instance if you call your function on list [2, 2, 4, 6, 1] it will delete the first 2 of your list then move to lst[1] which is 4 (after deletion of the first 2), delete this one then move to lst[2] which is now 1 and terminates. The resulting list will be [2, 6, 1]

修改正在迭代的结构是非常不好的做法.在这里,您应该首选 while 循环:

It is very bad practice to modify the structure you are iterating on. Here you should prefer a while loop:

def delete_starting_evens(lst):
    while len(lst) > 0 and lst[0]%2==0:
        lst.remove(lst[0])
    return lst

l = [2, 2, 4, 6, 1]
delete_starting_evens(l)
print(l)

这篇关于为什么我从列表开头删除偶数的代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆