提问人:Onik Rahman 提问时间:4/12/2022 最后编辑:Wiktor StribiżewOnik Rahman 更新时间:4/13/2022 访问量:252
如何从嵌套列表中删除匹配项?
How to remove matching item from nested list?
问:
我有一个包含列表的列表,我想从每个列表中删除一个通配符匹配项(如果存在),否则按原样返回。
例
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"],...]
有解决办法吗?
答:
2赞
Tim Biegeleisen
4/12/2022
#1
以下是使用嵌套 2D 列表推导执行此操作的一种方法:
nested_list = [["abc","fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","abcvs","ewq"]]
output = [[y for y in x if not re.search(r'^abc', y)] for x in nested_list]
print(output) # [['fds', 'gfssdf'], ['dfsdf', 'cds', 'dvc'], ['dsaf', 'ewq']]
0赞
0stone0
4/12/2022
#2
其他答案提供了一个很好的解决方案,但出于学习目的,我想回答 OP 的原始问题
你的代码中有一些错误,我将一一解决:
if re.search('abc.+', y) in x:
re.search
如果找不到,则返回,因此您可以删除None
in x
在搜索 1 个或更多时,由于要匹配,因此将 更改为 a 以匹配 0 或更多
+
abc.+
abc
+
?
如果您要从更深的列表中删除所有元素,您将以一个空列表结束 op,因此让我们为此添加一个检查并删除空列表:
if not x: nested_list.remove(x)
应用这些修复程序可以让我们:
import re
nested_list = [["abc","fds","gfssdf"],["dfsdf","cds","dvc"],["dsaf","abcvs","ewq"], ["abc"]]
for x in nested_list :
for y in x:
if re.search('abc.?', y):
x.remove(y)
if not x:
nested_list.remove(x)
print(nested_list)
女巫给出了预期的输出:
[['fds', 'gfssdf'], ['dfsdf', 'cds', 'dvc'], ['dsaf', 'ewq']]
正如您可以在此在线演示中测试的那样。
0赞
not_speshal
4/12/2022
#3
您也可以使用代替 :startswith
re
>>> [[y for y in x if not y.startswith("abc")] for x in nested_list]
[['fds', 'gfssdf'], ['dfsdf', 'cds', 'dvc'], ['dsaf', 'ewq']]
评论