有没有办法避免这么多列表(链(*list_of_list))?

Is there a way of avoiding so many list(chain(*list_of_list))?

如果我有一个包含两个字符串的元组列表的列表。我想把它展平成一个非嵌套的元组列表,我可以这样做:

>>> 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)) 的情况下解包到非嵌套元组列表?

解包迭代器之前不需要调用 list:

list(chain(*chain(*lllt)))

最好使用 chain.from_iterable 而不是解包,使用迭代器而不是使用 *:

将它们具体化为元组
flatten = chain.from_iterable
list(flatten(flatten(lllt)))

您可以继续解包直到找到元组:

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