Python Forum

Full Version: one comprehension with more elements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a list of 2-tuples like [(2,4),(3,9),{4,16),(5,25)...]. i would like to serialize/flatten all the elements of it like [2,4,3,8,4,16,5,25,...] and do it all in one comprehension (on one line). any ideas? how about a list of N-tuples?
It's pretty straight forward with that list.
>>> lst  = [(2,4),(3,9),(4,16),(5,25)]
>>> [i for sublist in lst for i in sublist]
[2, 4, 3, 9, 4, 16, 5, 25]
Make someone mad Angry
>>> lst  = [(2,4),(3,9),(4,16),(5,25)]
>>> list(sum(lst, ()))
[2, 4, 3, 9, 4, 16, 5, 25]
def flat_sequnce_gen(input_list, traverse=None, exclude=None):
    traverse = traverse or (list, tuple)
    exclude = exclude or (str, bytes, int, float, complex)
    iterators = [iter(input_list)]
    last = None
    while iterators:
        try:
            current = next(iterators[-1])
        except StopIteration:
            iterators.pop()
            continue
        if isinstance(current, traverse) and not isinstance(current, exclude):
            if last is current:
                yield current
                iterators.pop()
                continue
            iterators.append(iter(current))
            last = current
        else:
            yield current
Good luck with understanding the code. I wrote it a while before to have a generator, which can flat everything (if there is no bug).
wow! and you did it without recursion! i always love it when something that is "obiously" recursive can be done without recursion. in some situations, stack space can be rather limited. i might try to apply that logic to my print_object() function, which is using recursion.
In [1]: nested = [(2,4),(3,9),(4,16),(5,25)]

In [2]: def flatten(iterable):
   ...:     iterator = iter(iterable)
   ...:     for item in iterator:
   ...:         if '__iter__' in dir(item):
   ...:             yield from flatten(item)
   ...:             
   ...:         else:
   ...:             yield item
   ...:             

In [3]: flat = list(flatten(nested))

In [4]: flat
Out[4]: [2, 4, 3, 9, 4, 16, 5, 25]
It's is not a comprehension but it works with more dimensions. In such a case writing a list comprehension is exhausting.