pepe - 2 years ago 118

Python Question

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Use one of

`numpy.ravel`

returns a contiguous flattened array.`numpy.ndarray.flat`

returns a 1-D iterator over the array. (this is a`numpy.flatiter`

instance)`numpy.ndarray.flatten`

that returns a copy of the array collapsed into one dimension.

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]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**