我有这种列表列表(只有两个嵌套级别):
my_list = [['A'], ['B'], ['C','D','A','B'], ['E'], ['B', 'F', 'G'], ['H']]
我在my_list
中删除了要删除的项目列表:
to_del = ['A','B']
这是我想要删除to_del
中的my_list
元素的代码:
for i in my_list:
for d in to_del:
if d in i:
i.remove(d)
输出:
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
我的问题在这里:
my_list = [ ['A'], ['B'], ['C', ['D', 'E', ['F']], 'G'], ['H'] ]
empty_lists
来决定是否保留空列表。答案 0 :(得分:7)
尝试列表理解:
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
输出:
>>> my_list
[[], [], ['C', 'D'], ['E'], ['F', 'G'], ['H']]
答案 1 :(得分:3)
使用嵌套列表推导:
[[y for y in x if y not in to_del] for x in my_list]
使用列表理解和lambda过滤器:
[filter(lambda y: y not in to_del, x) for x in my_list]
尝试任意嵌套列表的一般情况:
def f(e):
if not isinstance(e,list):
if e not in to_del:
return e
else:
return filter(None,[f(y) for y in e])
to_del = ['A','B']
my_list= [['A'], ['B',['A','Z', ['C','Z','A']]], ['C','D','A','B'],['E'], ['B','F','G'], ['H']]
>>> f(my_list)
[[['Z', ['C', 'Z']]], ['C', 'D'], ['E'], ['F', 'G'], ['H']]