简体   繁体   中英

Remove tuple from nested list of tuples

I have a nested list as nested list of tuples as below,

nest_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]

I need to parse through the list and delete the tuples containing value 'bb' so that my final nested list would be as below

 final_nest_list= [[('aa','1')],[('cc','3')],[('dd','5'),('dd','6')]]

I tried to use nested "for loop" but doesn't seem to be efficient. Is there any "recursive way" of doing this in python, so that even the depth of nested list changes it should work.

One could easily use a list comprehension to remove the unwanted items, but considering the depth of nesting may vary, here's a recursive way to do it:

nest_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]


def remove_items(lst, item):
    r = []
    for i in lst:
        if isinstance(i, list):
            r.append(remove_items(i, item))
        elif item not in i:
            r.append(i)
    return r

>>> nest_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]
>>> remove_items(nest_list, 'bb')
[[('aa', '1')], [('cc', '3')], [('dd', '5'), ('dd', '6')]]

>>> nest_list= [[[('aa','1'),('bb','2')],[('cc','3'),('bb','4')]],[('dd','5'),('dd','6')]]
>>> remove_items(nest_list, 'bb')
[[[('aa', '1')], [('cc', '3')]], [('dd', '5'), ('dd', '6')]]

Make simple function.

def filter_bb(x):
    return [(u,v) for (u,v) in x if u !='bb']

Apply in list comprehension.

final_nest = [filter_bb(sub_list) for sub_list in nest_list]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM