删除列表的许多元素(python) [英] Delete many elements of list (python)

查看:74
本文介绍了删除列表的许多元素(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表L.

我可以通过以下操作删除元素i:

I can delete element i by doing:

del L[i]

但是如果我要删除一组非连续索引怎么办?

But what if I have a set of non contiguous indexes to delete?

I=set([i1, i2, i3,...])

正在做

for i in I: 
     del L[i]

不起作用.

有什么想法吗?

推荐答案

Eine Minuten Bitte,Ich hap eine 克莱因问题. -埃迪·伊扎德(Eddie Izzard)(给人留下深刻的印象 路德(Martin Luther)的照片

Eine Minuten bitte, Ich hap eine kleine Problemo avec diese Religione. -- Eddie Izzard (doing his impression of Martin Luther)

通过反向迭代列表以保留迭代器 进行删除是解决此问题的常见方法.但是另一个解决方案是将其变成一个不同的问题.不用使用某些条件从列表中删除项目(在您的情况下,该索引存在于要删除的索引列表中),而是创建一个新列表以排除有问题的项目.

Deleting by reverse-iterating over a list to preserve the iterator is a common solution to this problem. But another solution is to change this into a different problem. Instead of deleting items from the list using some criteria (in your case, the index exists in a list of indexes to be deleted), create a new list that leaves out the offending items.

L[:] = [ item for i,item in enumerate(L) if i not in I ]

为此,您首先从何处得出I中的索引?您可以结合获取要删除的索引并构建新列表的逻辑.假设这是一个对象列表,而您只想保留通过isValid测试的对象:

For that matter, where did you come up with the indexes in I in the first place? You could combine the logic of getting the indexes to be removed and building the new list. Assuming this is a list of objects and you only want to keep those that pass an isValid test:

L[:] = [ item for item in L if item.isValid() ]

这比以下内容简单得多:

This is much more straightforward than:

I = set()
for i in range(len(L)):
    if not L[i].isValid():
        I.add(i)

for i in sorted(I, reverse=True):
    del L[i]

在大多数情况下,我将有关如何从列表中删除不需要的项目"的任何问题变成如何创建仅包含所需项目的新列表"的问题.

For the most part, I turn any question about "how to delete from a list the items that I don't want" into "how to create a new list containing just the items I want".

根据Alex Martelli对

EDITED: changed "L = ..." to "L[:] = ..." per Alex Martelli's answer to this question.

这篇关于删除列表的许多元素(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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