程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python quick start (3rd Edition) Chapter 8-10 reading notes

編輯:Python

《Python Quick start ( The first 3 edition )》 Naomi · Sead

8.2 if-elif-else sentence

Python There is no case sentence . In most other languages case or switch Occasion of sentence ,Python It can be connected in series if...elif...elif...else Structure to deal with . If you encounter a few difficult occasions , Usually we can use function dictionary to solve

def do_a_stuff():
#process a
def do_b_stuff():
#process b
def do_c_stuff():
#process c
func_dict = {'a' : do_a_stuff,
'b' : do_b_stuff,
'c' : do_c_stuff }
x = 'a'
func_dict[x]()

for example ,

def do_a_stuff(a,b):
return a+b
def do_b_stuff(a,b):
return a-b
def do_c_stuff(a,b):
return a*b
func_dict = {'a' : do_a_stuff,
'b' : do_b_stuff,
'c' : do_c_stuff }
x = 'a'
y = func_dict[x](333,555)
print(y) # Output 888

8.3.1 range function

For the numbers given n,range(n) Returns the 0、1、2、……、n-2、n-1. therefore , Change list length ( call len function ) Incoming will produce a sequence of list element indexes .

>>> range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

If there are two numerical parameters , Then the first is the starting value of the result sequence , The second is the end value of the result sequence ( Not included ).

range The third optional parameter of the function , In order to give the step value when counting .

>>> list(range(2,8))
[2, 3, 4, 5, 6, 7]
>>> list(range(2,8,3))
[2, 5]
>>>

8.3.4 for Loop and tuple unpacking

The following code is in for Keywords are followed by tuples x,y, Instead of the usual single variable .

>>> somelist = [(1, 2), (3, 7), (9, 5)]
>>> result = 0
>>> for x, y in somelist:
... result = result + (x * y)
...
>>> result
68
>>>

8.3.5 enumerate function
enumerate The function returns tuples ( Indexes , Data item )
By combining tuple unpacking and enumerate function , It can realize circular traversal of data items and their indexes at the same time .

>>> x = [2, -3, 5, -7, -11]
>>> enumerate(x)
<enumerate object at 0x7f752b4ed090>
>>> list(enumerate(x))
[(0, 2), (1, -3), (2, 5), (3, -7), (4, -11)]
>>>
>>> for i,n in enumerate(x):
... if n < 0:
... print("Found a negative number at index:", i)
...
Found a negative number at index: 1
Found a negative number at index: 3
Found a negative number at index: 4
>>>

8.3.5 zip function

zip Function can read the corresponding elements one by one from one or more iteratable objects , And merge into tuples , Until the iterative object with the shortest length is read

>>> a = [1, 2, 3, 4]
>>> b = ['a', 'b', 'c', 'd', 'e', 'f']
>>> z = zip(a,b)
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>>

8.4 List and dictionary derivation

The usage of list derivation is as follows :
​​new_list = [expression1 for variable in old_list if expression2]

The usage of dictionary derivation is as follows :
​​new_dict = {expression1:expression2 for variable in list if expression3}​​

Generator Expressions
Be careful : Except for the change of square brackets , The generator expression does not return a list . The generator expression returns the generator object , It can be used as for Iterators in loops , This is related to range() The purpose of the function is very similar .
The advantage of using generator expressions is , The entire list will not be generated in memory . Therefore, a sequence of values of any size can be generated , Memory overhead is also small .

Hands on questions : The derivation is to remove the list x Negative number in , What list derivation should be used to deal with lists ?
Create can return 1 To 100 Between odd generators . Tips : Odd number divided by 2 There will be a remainder , The remainder can be used %2 Operate to get .
Write code to create a dictionary , The key is 11 To 15 Number between , The value is the cube of the bond .

1.
>>> x_nonegative = [ a for a in x if a >=0 ]
>>> x_nonegative
[11, 666, 5, 223, 886]
>>>
>>>
>>> x_nonegative = [ x for x in x if x >=0 ]
>>> x_nonegative
[11, 666, 5, 223, 886]
>>>
2.
>>> gen = (i for i in list(range(100)) if i % 2 !=0)
>>> next(gen)
1
>>> next(gen)
3
>>> next(gen)
5
>>> next(gen)
7
>>>
3.
>>> { key:key**3 for key in list(range(11,16))}
{11: 1331, 12: 1728, 13: 2197, 14: 2744, 15: 3375}
>>>

8.6 Boolean values and Boolean expressions

The operator and and or Object will be returned
and The operator either returns the first as False The object of ( The result of the expression ), Or return the last object .
or The operator either returns the first as True The object of , Or return the last object .

Most of the time , It's all about == and !=, instead of is and is not.is and is not Used to determine whether the operation object is the same object

9.4 local variable 、 Nonlocal variables and global variables
nonlocal Statements and global Statements like , It will make the identifier refer to the nearest closed scope (enclosing scope) Bound variables in .

example :

If you want to assign values to variables other than functions , It must be explicitly declared as nonlocal or global. But if you just want to access variables outside the function , It does not need to be declared as nonlocal or global.

9.6 lambda expression

​​lambda parameter1, parameter2, . . .: expression​​

>>> deg_C2K = lambda deg_C: 273.15 + deg_C
>>> deg_C2K(32)
305.15
>>>

9.8 Decorator

def decorate(func):
print("in decorate function, decorating", func.__name__)
def wrapper_func(*args):
print("Executing", func.__name__)
return func(*args)
return wrapper_func
def myfunction(parameter):
print(parameter)
myfunction = decorate(myfunction)
myfunction("hello")

Output results :
in decorate function, decorating myfunction
Executing myfunction
hello

Decorator (decorator) It is the grammatical sugar of the above process (syntactic sugar), Just adding a line of code can wrap one function into another . The effect is the same as the above code .

The decorator consists of two parts : First define for packaging or “ decorate ” Decorator functions of other functions ; Then immediately before the definition of the wrapped function , add “@” And decorator function name .

def decorate(func):
print("in decorate function, decorating", func.__name__)
def wrapper_func(*args):
print("Executing", func.__name__)
return func(*args)
return wrapper_func
@decorate
def myfunction(parameter):
print(parameter)
myfunction("hello")

Output results :
in decorate function, decorating myfunction
Executing myfunction
hello

Interactive mode

>>> def decorate(func):
... print("in decorate function, decorating", func.__name__)
... def wrapper_func(*args):
... print("Executing", func.__name__)
... return func(*args)
... return wrapper_func
...
>>> @decorate
... def myfunction(parameter):
... print(parameter)
...
in decorate function, decorating myfunction
>>>
>>> myfunction("hello")
Executing myfunction
hello
>>>

10.2 Write the first module

mymath.py The contents are as follows

"""mymath - our example math module"""
pi = 3.14159
def area(r):
global pi
return(pi * r * r)
>>> import mymath
>>> pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>>
>>> mymath.pi
3.14159
>>>

If you modify the module file in the disk , Then enter again import The command does not reload the module , At this time, we need to use modules importlib Of reload Function .importlib Module provides an interface for accessing the background mechanism of module import :

>>> mymath.pi
3.14159
>>> import mymath, importlib
>>> importlib.reload(mymath)
<module 'mymath' from '/root/mymath.py'>
>>> mymath.pi
3.14
>>>

When the module is reloaded ( Or import for the first time ) when , All the code will be parsed . If an error is found , Syntax exceptions will be thrown . conversely , If everything goes well, it will create a containing Python Bytecode .pyc file , Such as mymath.pyc.

10.4 Module search path
sys.path yes Python Path set of search module , It's a list

>>> sys.path
['', '/usr/local/python3/lib/python39.zip', '/usr/local/python3/lib/python3.9', '/usr/local/python3/lib/python3.9/lib-dynload', '/usr/local/python3/lib/python3.9/site-packages']
>>>

explain :sys.path The first element of is "", This will tell Python To find modules in the current directory .

10.5 Module internal private name

Identifiers beginning with underscores in modules cannot be used from module import * Import . The Convention of using leading underscores to indicate private names , Whole Python It's all in use , Not just in modules .

for example modtest.py The contents are as follows

def f(x):
return x
def _g(x):
return x
a = 4
_b = 2

Start an interactive session test

>>> from modtest import *
>>> f(3)
3
>>> _g(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_g' is not defined
>>>

Be careful : Only from <module> import * Will have such behavior . You can still access _g and _b Of :

Start an interactive session test

>>> import modtest
>>> modtest._g(3)
3
>>> modtest._b
2
>>>

Start an interactive session test

>>> from modtest import _g,_b
>>> _g(3)
3
>>> _b
2
>>>

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved