python - Remove tuple from nested list of tuples -


i have nested list nested list of tuples below,

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

i need parse through list , delete tuples containing value 'bb' final nested list below

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

i tried use nested "for loop" doesn't seem efficient. there "recursive way" of doing in python, depth of nested list changes should work.

one use list comprehension remove unwanted items, considering depth of nesting may vary, here's recursive way it:

nest_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]   def remove_items(lst, item):     r = []     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')]] 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -