从包含特定字符的列表中删除元素

时间:2021-04-07 20:26:22

I want to remove all elements in a list which contains (or does not contain) a set of specific characters, however I'm running in to problems iterating over the list and removing elements as I go along. Two pretty much equal examples of this is given below. As you can see, if two elements which should be removed are directly following each other, the second one does not get removed.

我想删除包含(或不包含)一组特定字符的列表中的所有元素,但是我正在遇到迭代列表并在我继续时删除元素的问题。下面给出两个几乎相同的例子。如您所见,如果要删除的两个元素直接相互跟随,则第二个元素不会被删除。

Im sure there are a very easy way to do this in python, so if anyone know it, please help me out - I am currently making a copy of the entire list and iterating over one, and removing elements in the other...Not a good solution I assume

我确定在python中有一个非常简单的方法可以做到这一点,所以如果有人知道它,请帮助我 - 我正在制作整个列表的副本并迭代一个,并删除另一个中的元素...不我假设一个好的解决方案

>>> l
['1', '32', '523', '336']
>>> for t in l:
...     for c in t:
...         if c == '2':
...             l.remove(t)
...             break
...             
>>> l
['1', '523', '336']
>>> l = ['1','32','523','336','13525']
>>> for w in l:
...     if '2' in w: l.remove(w)
...     
>>> l
['1', '523', '336']

Figured it out:

弄清楚了:

>>> l = ['1','32','523','336','13525']
>>> [x for x in l if not '2' in x]
['1', '336']

Would still like to know if there is any way to set the iteration back one set when using for x in l though.

仍然想知道是否有任何方法可以在使用for x in l时将迭代设置回一组。

3 个解决方案

#1


42  

List comprehensions:

>>> l = ['1', '32', '523', '336']
>>> [ x for x in l if "2" not in x ]
['1', '336']
>>> [ x for x in l if "2" in x ]
['32', '523']

#2


6  

If I understand you correctly,

如果我理解正确,

[x for x in l if "2" not in x]

might do the job.

可能会做这个工作。

#3


0  

Problem you could have is that you are trying to modify the sequence l same time as you loop over it in for t loop.

您可能遇到的问题是,您尝试修改序列,同时将其循环到t循环中。

#1


42  

List comprehensions:

>>> l = ['1', '32', '523', '336']
>>> [ x for x in l if "2" not in x ]
['1', '336']
>>> [ x for x in l if "2" in x ]
['32', '523']

#2


6  

If I understand you correctly,

如果我理解正确,

[x for x in l if "2" not in x]

might do the job.

可能会做这个工作。

#3


0  

Problem you could have is that you are trying to modify the sequence l same time as you loop over it in for t loop.

您可能遇到的问题是,您尝试修改序列,同时将其循环到t循环中。