Python Forum
one comprehension with more elements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
one comprehension with more elements
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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]
Reply
#3
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).
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 470 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,115 May-17-2022, 11:38 AM
Last Post: Larz60+
  Sorting Elements via parameters pointing to those elements. rpalmer 3 2,585 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  need 2x elements in list comprehension Skaperen 7 4,363 Apr-30-2018, 02:16 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020