如何从嵌套列表中删除匹配项目?
我有一个带有列表的列表,如果存在的话,我想从每个列表中删除一个通配符匹配的项目,否则将其返回。
例如,
nested_list = [["abc","fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","abcvs","ewq"],...]
我尝试做的是:
for x in nested_list :
for y in x:
if re.search('abc.+', y) in x:
nested_list.remove(x)
但是它返回相同的列表,而没有任何更改
我所需的输出将是:
nested_list = [["fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","ewq"],...]
有解决方案吗?
I have a list with lists and I would like remove a wildcard matching item from each list if present, otherwise return it as it is.
Example
nested_list = [["abc","fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","abcvs","ewq"],...]
What I tried to do is:
for x in nested_list :
for y in x:
if re.search('abc.+', y) in x:
nested_list.remove(x)
However it returns the same list, without any changes
My desirable output would be:
nested_list = [["fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","ewq"],...]
Is there a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种使用嵌套的2D列表理解的一种方法:
Here is one way to do this with a nested 2D list comprehension:
您也可以使用
startswith
而不是re
进行此操作:You could also do this using
startswith
instead ofre
:其他答案正在提供一个不错的解决方案,但我想回答OP的原始问题以学习目的,
您有一些错误代码,我将对它们一个一个一个:
如果re.search('abc。+',y),x:
re.search
返回none
如果找不到,则可以在x中删除
中删除
在
abc。+
搜索1或更多中,由于要匹配abc
,请将+
更改为?匹配0或更多
如果您要从更深层列表中删除所有元素,则将用空列表结束OP,因此,让我们添加检查并删除空列表:
应用这些修复程序给了我们:
女巫给出了预期的输出:
当您can test in this online demo 。
The other answers are providing a nice solution, but I wanted to answer OP's original question for learning purposes
There are some mistakes in your code, I'll adress them one by one:
if re.search('abc.+', y) in x:
re.search
returnsNone
if it's not found, so you can remove thein x
The
+
inabc.+
searched for 1 or more, since you want to matchabc
, change the+
to a?
to match 0 or moreIf you'd remove all the elements from an deeper list, you'll end op with a empty list, so lets add a check for that and remove the empty list:
Applying those fixes gives us:
Witch gives the expected output:
As you can test in this online demo.