Flatten usage in Pythonoriginal April 16, 2014 10:20:02
One, used in the array
[Python]View PlainCopy
- >>> a = [[1,3],[2,4],[3,5]]
- >>> A = Array (a)
- >>> A.flatten ()
- Array ([1, 3, 2, 4, 3, 5])
Second, use in the list
If you use the Flatten function directly, you will get an error
[Python]View PlainCopy
- >>> a = [[1,3],[2,4],[3,5]]
- >>> A.flatten ()
- Traceback (most recent):
- File "<pyshell#10>", line 1, in <module>
- A.flatten ()
- Attributeerror: ' List ' object has no attribute ' flatten '
The right usage
[Python]View PlainCopy
- >>> 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 (not understood)
[Python]View PlainCopy
- >>> 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 els e [x]
- >>> Flatten (a)
- [1, 3, 2, 4, 3, 5, ' abc ', ' def ']
Third, used in the matrix
[Python]View PlainCopy
- >>> 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])
Flatten usage in Python