pepe pepe - 6 months ago 28
Python Question

How to flatten zipped object containing nested arrays to a list?

I have a zipped object like this:

z = zip(a, b)
lst = list(z)

print(lst)


Output:

[(0, array([[72, 65],
[70, 71]], dtype=uint8)),
(1, array([[ 71, 99],
[190, 163]], dtype=uint8)),
(2, array([[52, 59],
[69, 72]], dtype=uint8)), etc...


I would like to flatten this list to the following:

[0, 72, 65, 70, 71, 1, 71, 99, 190, 163, 2, 52, 59 etc..]


I've tried doing this with

y = sum(w, ())
# or
y = list(itertools.chain(*lst))


But the arrays are still there when I print.

What am I doing wrong?

Answer

Use one of

Here is a MWE.

import numpy as np

lists = [(0, np.array([ [72,  65],
                        [70,  71]], dtype=np.uint8)), 
        (1, np.array([  [71,  99],
                        [190, 163]], dtype=np.uint8))]

l = list()
for idx, array in lists:
    l.append(idx)
    l.extend(np.ravel(array))   # returns a contiguous flattened array
    #l.extend(array.flat)       # return a 1-D iterator over the array.
    #l.extend(array.flatten())  # return a copy of the array collapsed into one dimension 

print(l)
# Output
[0, 72, 65, 70, 71, 1, 71, 99, 190, 163]
Comments