Flatten usage in Python

Source: Internet
Author: User

Flatten usage in Pythonoriginal April 16, 2014 10:20:02
    • Label:
    • Python/
    • Flatten
    • 22667
One, used in the array

[Python]View PlainCopy
    1. >>> a = [[1,3],[2,4],[3,5]]
    2. >>> A = Array (a)
    3. >>> A.flatten ()
    4. 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
    1. >>> a = [[1,3],[2,4],[3,5]]
    2. >>> A.flatten ()
    3. Traceback (most recent):
    4. File "<pyshell#10>", line 1, in <module>
    5. A.flatten ()
    6. Attributeerror: ' List ' object has no attribute ' flatten '

The right usage

[Python]View PlainCopy
    1. >>> a = [[1,3],[2,4],[3,5],["abc","Def"]]
    2. >>> a1 = [Y for X in a for y in x]
    3. >>> A1
    4. [1, 3, 2, 4, 3, 5, ' abc ', ' def ']

or (not understood)

[Python]View PlainCopy
  1. >>> a = [[1,3],[2,4],[3,5],["abc","Def"]]
  2. >>> flatten = lambda x: [Y for L in X for y in flatten (l)] if Type (x) is list els e [x]
  3. >>> Flatten (a)
  4. [1, 3, 2, 4, 3, 5, ' abc ', ' def ']

Third, used in the matrix [Python]View PlainCopy
  1. >>> a = [[1,3],[2,4],[3,5]]
  2. >>> A = Mat (a)
  3. >>> y = A.flatten ()
  4. >>> y
  5. Matrix ([[[1, 3, 2, 4, 3, 5]])
  6. >>> y = A.flatten (). A
  7. >>> y
  8. Array ([[1, 3, 2, 4, 3, 5]])
  9. >>> shape (y)
  10. (1, 6)
  11. >>> shape (y[0])
  12. (6,)
  13. >>> y = A.flatten (). a[0]
  14. >>> y
  15. Array ([1, 3, 2, 4, 3, 5])

Flatten usage in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.