Skip to content Skip to sidebar Skip to footer

Is There A Way Of Avoiding So Many 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 >&g

Solution 1:

You don't need to call list before unpacking an iterator:

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

It may be better to use chain.from_iterable rather than unpacking, to work with iterators instead of materializing them into tuples with *:

flatten = chain.from_iterable
list(flatten(flatten(lllt)))

Solution 2:

You could keep unpacking until you hit tuples:

defunpack_until(data, type_):
    for entry in data:
        ifisinstance(entry, type_):
            yield entry
        else:
            yieldfrom unpack_until(entry, type_)

Then:

>>> list(unpack_until(lllt, tuple))
[('ab', 'cd'),
 ('ef', 'gh'),
 ('ij', 'kl'),
 ('mn', 'op'),
 ('qr', 'st'),
 ('uv', 'w'),
 ('x', 'y'),
 ('z', 'foobar')]

Post a Comment for "Is There A Way Of Avoiding So Many List(chain(*list_of_list))?"