从包含特定字符的列表中删除元素 [英] Removing elements from a list containing specific characters

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

问题描述

我想删除列表中包含(或不包含)一组特定字符的所有元素,但是我正在运行在迭代列表中的问题,并删除元素。下面给出了两个相当的例子。如你所见,如果两个要删除的元素是直接相互关联的,那么第二个元素就不会被删除。

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.

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

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

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

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

仍然想知道在l中使用x时是否有任何方法将迭代设置为一组。

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

推荐答案

列表解析:

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

这篇关于从包含特定字符的列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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