flatten and of functions in Python

  • 2021-01-25 07:44:15
  • OfStack

flatten() function usage

flatten is a function of numpy.ndarray.flatten that returns a 1-dimensional array.

flatten only applies to numpy objects, that is, array or mat, normal list lists do not apply! .

a.flatten () : a is an array, a.flatten () reduces a to 1 dimension, by default, in line direction.
a.flatten().A: a is a matrix, which is reduced in dimension to a matrix. Consider the following example:

1, Used for ES32en objects


>>> from numpy import *
>>> a=array([[1,2],[3,4],[5,6]])
>>> a
array([[1, 2],
    [3, 4],
    [5, 6]])
>>> a.flatten() # Default dimension reduction in the direction of the row 
array([1, 2, 3, 4, 5, 6])
>>> a.flatten('F') # According to the column dimension reduction 
array([1, 3, 5, 2, 4, 6]) 
>>> a.flatten('A') # According to dimension reduction 
array([1, 2, 3, 4, 5, 6])
>>>

2. Used for mat objects


>>> a=mat([[1,2,3],[4,5,6]])
>>> a
matrix([[1, 2, 3],
    [4, 5, 6]])
>>> a.flatten()
matrix([[1, 2, 3, 4, 5, 6]])
>>> a=mat([[1,2,3],[4,5,6]])
>>> a
matrix([[1, 2, 3],
    [4, 5, 6]])
>>> a.flatten()
matrix([[1, 2, 3, 4, 5, 6]])
>>> y=a.flatten().A 
>>> shape(y)
(1L, 6L)
>>> shape(y[0]) 
(6L,)
>>> a.flatten().A[0] 
array([1, 2, 3, 4, 5, 6])
>>> 

You can see the usage of matrix.A and the changes to the matrix.

3. This method does not work with list objects. To achieve the same effect with list, you can use a list expression:


>>> a=array([[1,2],[3,4],[5,6]])
>>> [y for x in a for y in x]
[1, 2, 3, 4, 5, 6]
>>> 
 ! 

Let's look at the usage of flatten in Python

1. Used in arrays


>>> a = [[1,3],[2,4],[3,5]]
>>> a = array(a)
>>> a.flatten()
array([1, 3, 2, 4, 3, 5])

2. Use it in lists

If you use the flatten function directly, you will get an error


>>> a = [[1,3],[2,4],[3,5]]
>>> a.flatten()

Traceback (most recent call last):
 File "<pyshell#10>", line 1, in <module>
  a.flatten()
AttributeError: 'list' object has no attribute 'flatten'

Proper usage


>>> a = [[1,3],[2,4],[3,5],["abc","def"]]
>>> a1 = [y for x in a for y in x]
>>> a1
[1, 3, 2, 4, 3, 5, 'abc', 'def']

Or (don't understand)


>>> a = [[1,3],[2,4],[3,5],["abc","def"]]
>>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
>>> flatten(a)
[1, 3, 2, 4, 3, 5, 'abc', 'def']

3. Used in matrices


>>> a = [[1,3],[2,4],[3,5]]
>>> a = mat(a)
>>> y = a.flatten()
>>> y
matrix([[1, 3, 2, 4, 3, 5]])
>>> y = a.flatten().A
>>> y
array([[1, 3, 2, 4, 3, 5]])
>>> shape(y)
(1, 6)
>>> shape(y[0])
(6,)
>>> y = a.flatten().A[0]
>>> y
array([1, 3, 2, 4, 3, 5])

conclusion


Related articles: