将元组从嵌套列表中分离到单独的列表中 [英] Separate tuple from a nested list into a separate list
本文介绍了将元组从嵌套列表中分离到单独的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据值从嵌套字典中分离出一个元组,如下所示,并将其放在另一个列表中.我想用值'bb'分隔元组
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')]]
我需要两个如下列表,
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?
推荐答案
>>> 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')]]
>>>
这篇关于将元组从嵌套列表中分离到单独的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文