Python _ advanced features

Source: Internet
Author: User
Tags iterable

Python _ advanced features
Python advanced features

Author: lxy


Slicing, iteration, list generation, generator


Slice
The less code Python, the simpler the better,
We want to take a part of the element in a list. We can use the judgment + loop implementation. In Python, we provide a special method-slicing.

Slice used to obtain an element in the list

Tuple, str, and so on are both regarded as a list of fragments obtained by using slices or their original corresponding types.

Example 1. Slice the list
  1. >>> N = [1, 3, 2, 5, 6, 8]
  2. >>> N [0: 3] # tail excluded
  3. [1, 3, 2]
  4. >>> N [-2:] # You can use reverse truncation.
  5. [6, 8]
  6. >>> Copy the code
    Example 2. Slice tuple
    1. >>> T = ('A', 's', 'D', 'D ')
    2. >>> T [: 3] # truncated from 0 by default
    3. ('A', 's', 'D') # tuple
    4. >>> Copy the code
      Example 3. segment str
      1. >>> S = 'dfsafsf'
      2. >>> S [: 3]
      3. 'Dfs '# string slices or strings
      4. >>># No function exists for string Truncation in Python. You only need to use slice to copy the code.


        Iteration
        It is called iteration.
        In c or Java, iterative list is done by subscript.
        Objects such as list can complete iteration with a lower mark, while dict, str, and so on can complete iteration without a lower mark through Python's for... in.
        Itervalues () can be used to iterate the v
        You can use iteritems () to iterate the k_V of dict.

        How to determine whether an object can be iterated
        Determined by the iterable type of the collections Module

        Example:
        1. >>> From collections import Iterable # obtain the Iterable type of the collections Module
        2. >>> Isinstance ('dfdas', Iterable) # determine whether iteration is allowed
        3. True
        4. >>> Isinstance (555, Iterable)
        5. False
        6. >>> Copy the code


          Implement subscript loop in Python. The Python built-in enumerate function can convert a list into an index-element.
          Example:
          1. >>> For I, v in enumerate ('s ', 'D', 'G ')):
          2. Print (I, v)
          3. 0 s
          4. 1 d
          5. 2g
          6. >>> Copy the code

            List Generator
            Range ()#
            1. Generate a continuous integer sequence through range ()
            2. pass -- <表达式> -- Generate a list


            Example 1: generate an integer Sequence
            1. >>> A = range (3)
            2. >>> For I in:
            3. Print (I)
            4. 0
            5. 1
            6. 2
            7. >>> Copy the code

              Example 2: generate a special number
              1. >>> C = [x * x for x in range (2, 5)]
              2. >>> C
              3. [4, 9, 16]
              4. >>> Copy the code

                Adding if and nested in list generation
                Filter Using if
                Example,
                1. >>> A = [x * x for x in range (5) if x> 2] # Add if to filter x.
                2. >>>
                3. [9, 16]
                4. >>> Copy the code

                  Example,
                  1. >>> [M + n for m in 'abc' for n in 'xyz']
                  2. ['Ax ', 'ay', 'az', 'bx ', 'by', 'bz', 'cx', 'cy ', 'cz']
                  3. >>> Copy the code

                    For example, use the list generator to list all folders and directory names in the current directory.
                    1. >>> Import OS # import OS Module
                    2. >>> [D for d in OS. listdir ('.')] # The specified path is in brackets.
                    3. ['Dls', 'Doc', 'include ', 'lib', 'libs', 'scripts', 'tcl', 'tools']
                    4. >>> Copy the code

                      Generator
                      However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million elements not only occupies a large storage space, but if we only need to access the first few elements, the space occupied by the vast majority of elements is wasted.
                      Python provides this solution. The list elements are computed through an algorithm, and the subsequent elements are constantly computed during the loop process without the need to create a complete list.
                      Python stores algorithms and calls next () each time ()


                      Create generator
                      1. Change [] of the List generation type ()
                      2. After the yield keyword is added to a common function, this function is not a common function, but a generator function, which is executed every time next () is called, when the yield statement is returned, the yield statement is returned from the previous execution.

                      Example 1,
                      1. >>> B = (x for x in range (10 ))
                      2. >>> B
                      3. At 0x02CB1418>
                      4. >>> Next (B) # obtain the next element. Because generator is also iteratable, The for loop is generally used for iteration.
                      5. 0
                      6. >>> Copy the code

                        Example 2,
                        1. >>> Def f ():
                        2. Print ('s1 ')
                        3. Yield 1
                        4. Print ('s2 ')
                        5. Yield 2

                        6. >>> A = f ()
                        7. >>> Next ()
                        8. S1
                        9. 1
                        10. >>> Next ()
                        11. S2
                        12. 2
                        13. >>> Next ()
                        14. Traceback (most recent call last ):
                        15. File" ", Line 1, in
                        16. Next ()
                        17. StopIteration # An error is thrown when yield is not available for execution.
                        18. >>> Copy the code

                          The generator command after function transformation ends when return or function body is completed,

                          Example:
                          1. >>> Def f ():
                          2. Print ('s1 ')
                          3. Yield 1
                          4. Return
                          5. Print ('s2 ')
                          6. Yield 2

                          7. >>> For I in f ():
                          8. Print (I)


                          9. S1
                          10. 1
                          11. >>>>>> Def f ():
                          12. Print ('s1 ')
                          13. Yield 1
                          14. Return
                          15. Print ('s2 ')
                          16. Yield 2

                          17. >>> For I in f ():
                          18. Print (I)

                          19. S1
                          20. 1
                          21. >>> Copy the code























                            From group: Java User Group

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.