Separate tuple from a nested list into a separate list

假如想象 提交于 2020-01-03 00:57:07

问题


I need to separate a tuple based on a value from a nested dictionary as below and put it in another list. I want to separate tuple with values 'bb'

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

I need two lists as below,

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

I used the following recursive code,

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

It could produce the result list after deleting the value. Is there a way to get another list with the deleted values?


回答1:


>>> def remove_items(lst, item):
...     r = []
...     d = []
...     for i in lst:
...         if isinstance(i, list):
...             r_tmp,d_tmp = remove_items(i, item)
...             if r_tmp:
...                 r.append(r_tmp)
...             if d_tmp:
...                 d.append(d_tmp)
...         else:
...                 if item not in i:
...                     r.append(i)
...                 else:
...                     d.append(i)
...     return r,d
... 
>>> original_list= [[('aa','1'),('bb','2')],[('cc','3'),('bb','4')],[('dd','5'),('dd','6')]]
>>> result = remove_items(original_list,'bb')
>>> result[0]
[[('aa', '1')], [('cc', '3')], [('dd', '5'), ('dd', '6')]]
>>> result[1]
[[('bb', '2')], [('bb', '4')]]
>>> 


来源:https://stackoverflow.com/questions/40523759/separate-tuple-from-a-nested-list-into-a-separate-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!