Python 从列表中删除项目 [英] Python removing items from list

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

问题描述

我有一个给定格式的列表:

I have a list in the given format:

[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]

列表 ['Linus Torvalds', ''] 中有一些类似的元素,我想删除它们.那么为什么下面的代码没有删除它们呢?

There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them?

for i in people:
    if(i[0] == '' or i[1] == ''):
        print people.pop(people.index(i))

推荐答案

您在迭代列表时正在更改列表,这就是问题的根源.一种有效的方法是

You are changing the list while iterating over it and this is the source of your problems. An approach that works is

people[:] = [p for p in people if p[0] != '' and p[1] != '']

这样就构建了一个仅包含您想要的元素的新临时列表,然后在操作完成时将其分配给原始列表对象.

this way a new temporary list containing only the elements you want is built and then assigned to the original list object when the operation is complete.

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

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