Python derivations, iterators, generators, modules, and packages

Source: Internet
Author: User
Tags generator generator

First, the derivation of the formula

(i). List derivation (set deduction also applies to this)

Use list derivation to remove all even numbers within 1-20

Li = [i for I in range (1, +) if I% 2 = = 0] # If there is only one condition, write the IF statement on the last side

The first I is the value put in the list, followed by the deduced formula

Print (LI)

The first I corresponds to append (i) in the following equivalence scheme. Replace I with "a", the output list is all "a" equivalent to

For I in Range (1,21):
If i%2==0:
Li.append (LI)
Print (LI)

Use the list derivation to remove all numbers within 1-20. Where the odd number is replaced with the character "a", even the output is normal

Li = [i if I% 2 = = 0 Else "A" for I in range (1, 21)] # When adding multiple conditions, write in front
Print (LI)

List deduction Exercise: Reverse the list li=[' a ', ' B ', ' C ', ' d ', ' e ']

Print ([Li.pop () for I in Range (Len (LI))])

Pop () function, remove and return the last element

(ii). Dictionary derivation formula

Example 1:
A = {str (i): I for I in range (5)}
Print (a) # {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4}

Example 2:
A = {"I": I for I in range (5)}
Print (a) # {' I ': 4}

Because the dictionary key is unique, "Example 2" in the derivation, the name of the key to write dead, each deduction is in fact, the original value is modified.

Example 3:
Print ({i: ' A ' for I in range (5)})

{0: ' A ', 1: ' A ', 2: ' A ', 3: ' A ', 4: ' A '}

"Example 3" is to write the value to the dead. Equivalent to Dict.fromkeys ([0,1,2,3,4], "a")

(c). Ganso, is to return a generator object:
Print ((i-I in range (5)))

<generator Object

You need to use tuple () to view:
Print (Tuple (i-I in range (5)))

(0, 1, 2, 3, 4)

Second, iterators

To see if an object can be iterated, using the Dir (Li) method, the result of "iter" is an iterative one.

Using Dir (LI), it is considered an iterator to have "iter" and "next".

An enumeration is an iterator.

g = Enumerate ([1, 2, 3])
Print (dir (g))

After Dir (g), you can see the " ITERand Next"

(i). __iter__ () and next():

(1). __ITER__ () turns an iterative object into an iterator.
Li = [1, 2, 3]
g = li.__iter__ () # Use this method to become an iterator
Print (g.__next__ ()) # Implementing Iterators (Popular understanding: taking values)

To assign a value to a variable. Otherwise, the __next__ () is always the first value to write, and the first value in the iterator will never be taken.

Print (li.__iter__ (). __next__ ())
Print (li.__iter__ (). __next__ ())
Print (li.__iter__ (). __next__ ())

Here it is understood:! Iterator object, you must assign a value to a variable to accept!

(2). __NEXT__ (), implementing an iterator, essentially removing the next element of the iterator. Note: If the element is finished, then next () will report stopiteration exception!
Li = [1, 2, 3]
g = iter (LI)
Print (Next (g)) # The first element has been removed here.
Print ("---")
For i in G: # So this will only take out the 2 values in the back.
Print (i)

Third, generator generator

In Python, a function that uses the keyword yield is used as the generator. Essentially an iterator, keyword: yield

Unlike a normal function, a generator is a function that returns an iterator that can only be used for iterative operations.

In the process of calling the generator to run, each time yield is encountered, the function pauses and saves all current run information, returning the value of yield. and continue running from the current location the next time the next () method is executed. :

A simple generator is shown as follows:
def fun ():
i = 1
While I < 5:
Print (i)
# yield # Implements the functionality of the generator. 1, pause, 2, return value.
Yield "Stop" # can write like this, return a message
i + = 1
Print ("* *", i)
Print (Fun ()) # Here's a memory address returned
f = Fun ()
Print (Next (f))

Demonstrate Fibonacci with yield:
Def Fab (max_num):
N, a, b = 0, 0, 1
While N < max_num:
Yield "Pause print B:", b
A, B = B, A + b
n + = 1
For x in Fab (20):
Print (x)

Iv. Modules and Packages

(a). Module: is essentially a py file. Divided into: Built-in modules, third-party modules.

(1). Use of built-in modules:

Importing everything: import modulename; it's intuitive, but it takes up a lot of memory.

Specify import: from modulename import funcationname; know exactly what you want to use.

(2). Use of custom modules:

is a sibling path to the current PY file: Import directly.

References for different path imports:
Import SYS # Don't forget to pilot this.
Sys.path # The path is first tuned out. Returns a list, which is the installation directory for Python
Sys.path.append (R "") # parentheses can add the absolute path of their PY file, remember to cancel escape

and then import modulename.

(3). You have to add the last line of the Py file that you wrote:
If name = = 'main':
Functionname1 ()
Functionname2 ()

There is this piece of code. The test is either in itself or imported. Must be executed on the py file itself, run, will have the results.

(b). Package: Many py files are placed in a folder.

(iii). If name = = 'main':

is a if judgment, 'main' is a string, judging whether it is imported or executed directly.

When import a py module (file), the Py module (file) will be executed once.

Example 1:

I have a "test1.py" module (file) with the following code:
Import Test2

Print (name) # main
Print (test2.__name__) # Test2

"""
Operation Result:

fengzi111
Main
Test2
"""

There is another "test2.py" file with the following code:
Print ("fengzi111")

If name = = 'main':
Print ("fengzi222")

"test1.py", import "Test2", then "test2.py" was executed once. So in the "test1.py" Run results, will appear fengzi111, because import test2, "test2.py" was executed once.

Why can't I print the fengzi222?

"test2.py" is introduced into the "test1.py". In "test2.py" there is the if judgment, the result of judgment: they are two not the same name.

Look at the code print (test2.__name__) in the "test1.py" file, which deliberately shows what the name "test2.py" is. The result returned is test2, but now the "test1.py" file is executed! "Test1" = = "Test2"? Obviously false, then there will be no fengzi222.

Python derivations, iterators, generators, modules, and packages

Related Article

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.