Posts: 4,647
Threads: 1,494
Joined: Sep 2016
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.
Posts: 7,320
Threads: 123
Joined: Sep 2016
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
>>> lst = [(2,4),(3,9),(4,16),(5,25)]
>>> list(sum(lst, ()))
[2, 4, 3, 9, 4, 16, 5, 25]
Posts: 2,127
Threads: 11
Joined: May 2017
Mar-28-2018, 01:43 PM
(This post was last modified: Mar-28-2018, 01:43 PM by DeaD_EyE.)
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).
Posts: 4,647
Threads: 1,494
Joined: Sep 2016
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.
Posts: 2,953
Threads: 48
Joined: Sep 2016
Mar-31-2018, 02:47 AM
(This post was last modified: Mar-31-2018, 02:47 AM by wavic.)
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.
|