2016-11-10 82 views
1

我需要根据下面的嵌套字典中的值分开一个元组,并将它放在另一个列表中。我想和值“BB”从嵌套列表中分离元组到一个单独的列表

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

我需要如下两个列表,

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

我用下面的递归代码中分离出来的元组,

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 

它可能产生的结果删除值后列出。有没有办法用删除的值获得另一个列表?

回答

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