从列表列表中删除项目:pythonic方式

问题描述:

我有这种列表列表(只有两个嵌套级别):

I've this kind of list of list (only two nested level):

my_list = [['A'], ['B'], ['C','D','A','B'], ['E'], ['B', 'F', 'G'], ['H']]

我有一个要在my_list中删除的项目列表:

I've a list of items to delete in my_list:

to_del = ['A','B']

这是我从my_list删除to_del元素的代码的想法:

this is my idea of code to delete to_del elements from 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']]

这是我的问题:

  • 您能建议一种更pythonic/优雅的方法来做到这一点
  • 您能建议一种明智的方法来概括嵌套级别的数量吗? 例如my_list = [ ['A'], ['B'], ['C', ['D', 'E', ['F']], 'G'], ['H'] ]
  • 理想方法将具有一个布尔参数empty_lists来决定是否保留空列表.
  • Can you suggest a more pythonic/elegant way to do the same
  • Can you suggest a smart way to generalize the number of nested levels e.g my_list = [ ['A'], ['B'], ['C', ['D', 'E', ['F']], 'G'], ['H'] ]
  • The ideal method will have a boolean argument empty_lists to decide whether or not keep empty lists.

具有嵌套列表理解:

[[y for y in x if y not in to_del] for x in my_list]

具有列表理解和lambda过滤器:

With list comprehension and lambda filter:

[filter(lambda y: y not in to_del, x) for x in my_list]

尝试任意嵌套列表的一般情况:

An attempt for the general case of arbitrarily nested lists:

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