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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3416401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:56:47  来源:igfitidea点击:

Removing elements from a list containing specific characters

pythonlistdata-structures

提问by Vidar

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 时是否有任何方法可以将迭代设置回一组。

采纳答案by MattH

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']

回答by loevborg

If I understand you correctly,

如果我理解正确的话,

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

might do the job.

可能会做这项工作。

回答by Tony Veijalainen

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.

您可能遇到的问题是,您正试图在 for t 循环中循环的同时修改序列 l。

回答by J.Doe

In addition to @Matth, if you want to combine multiple statements you can write:

除了@Matth,如果你想组合多个语句你可以写:

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