如何在循环中从python列表中删除项目? [英] How to remove item from a python list in a loop?

查看:89
本文介绍了如何在循环中从python列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在Python中进行迭代时从列表中删除项目

Possible Duplicate:
Remove items from a list while iterating in Python

我正在尝试从python列表中删除一个项目:

I'm trying to remove an item from a list in python:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x:
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))
        x.remove(item)

但是它不会删除"fren"项目.有什么想法吗?

But it doesn't remove "fren" item. Any ideas?

推荐答案

在迭代列表时,无法从列表中删除项目.在旧清单的基础上建立新清单要容易得多:

You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:

y = [s for s in x if len(s) == 2]

这篇关于如何在循环中从python列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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