本文介绍了有没有办法避免这么多的list(chain(* list_of_list))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个字符串的元组列表的列表.我想将其展平为一个非嵌套的元组列表,我可以这样做:
If I have a list of list of list of tuples of two strings. I want to flatten it out to a non-nested list of tuples, I could do this:
>>> from itertools import chain
>>> lst_of_lst_of_lst_of_tuples = [ [[('ab', 'cd'), ('ef', 'gh')], [('ij', 'kl'), ('mn', 'op')]], [[('qr', 'st'), ('uv', 'w')], [('x', 'y'), ('z', 'foobar')]] ]
>>> lllt = lst_of_lst_of_lst_of_tuples
>>> list(chain(*list(chain(*lllt))))
[('ab', 'cd'), ('ef', 'gh'), ('ij', 'kl'), ('mn', 'op'), ('qr', 'st'), ('uv', 'w'), ('x', 'y'), ('z', 'foobar')]
但是,还有没有嵌套list(chain(*lst_of_lst))
到非嵌套元组列表的另一种方法吗?
But is there another way of unpacking to the non-nested list of tuples withou the nested list(chain(*lst_of_lst))
?
推荐答案
您可以继续打开包装,直到遇到元组为止:
You could keep unpacking until you hit tuples:
def unpack_until(data, type_):
for entry in data:
if isinstance(entry, type_):
yield entry
else:
yield from unpack_until(entry, type_)
然后:
>>> list(unpack_until(lllt, tuple))
[('ab', 'cd'),
('ef', 'gh'),
('ij', 'kl'),
('mn', 'op'),
('qr', 'st'),
('uv', 'w'),
('x', 'y'),
('z', 'foobar')]
这篇关于有没有办法避免这么多的list(chain(* list_of_list))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!