Installation operation
- Create a new Python /1.py file in Visual Studio Code and type save.
#! /usr/bin/env python3 print(100+200+300)Copy the code
- Open the terminal in the Python folder and type
chomd a+x 1.py
In the input./1.py
, the run result 600 appears.
Python based
Input and output
1.print
2. input
Input () returns STR. STR cannot be compared directly with an integer. STR must be converted to an integer first. Python provides the int() function to do this
S = input('birth: ') birth = int(s) if birth < 2000: print('00 ') else: print('00 ')Copy the code
conditional
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
Copy the code
cycle
The for… in
- Iterate through each element in a list or tuple in turn
Names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) This code will print each element of names in sequence, i.e. Michael Bob TracyCopy the code
The range () function
, can generate a sequence of integers, which can be converted to list by the list() function. For example, range(101) generates a sequence of integers starting from 0 and less than 101, that is, a sequence of integers from 0 to 100. Calculate the sum of 1-100 steaming:
# -*- coding: utf-8 -*-
sum = 0
for x in range(101):
sum = sum + x
print(sum)
Copy the code
while
- Calculate the sum of all odd numbers up to 100:
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
Copy the code
break
Exit the loop early.
Print (n) n = n + 1 print('END') print('END')Copy the code
continue
Skip the current loop and start the next one.
While n < 10: n = n + 1 if n % 2 == 0: # If n is even, execute the continue statement continue # continue the next loop directly, the subsequent print() statement does not execute print(n)Copy the code
Dic and set
dic
Python has built-in support for dictionaries: dict, which stands for dictionary and is also called map in other languages. It uses key-value storage for extremely fast lookups.
- Dict to find names, only need a “name” – “score” comparison table, directly according to the name to find results, no matter how big the table, the search speed will not slow down. Write a dict in Python like this:
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
Copy the code
Avoid key nonexistence
There are two ways to make a mistake.
1. Check whether key exists >>> 'Thomas' in d False 2. Dict provides a get() method that returns None if the key does not exist, or a self-specified value: >>> d.set ('Thomas') >>> d.set ('Thomas', -1) -1 Python's interactive environment does not display results when None is returned.Copy the code
- to
delete
A key, with the pop(key) method, is also removed from the dict:
>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}
Copy the code
- The dict key must be
Immutable object
.- In Python, strings, integers, and so on are immutable and can be safely used as keys. while
List is mutable
, cannot be used as key:
- In Python, strings, integers, and so on are immutable and can be safely used as keys. while
>>> key = [1, 2, 3]
>>> d[key] = 'a list'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Copy the code
List compared to dict
- Dict:
- Lookups and inserts are extremely fast and do not slow down as keys are added;
- Need to take up a lot of memory, memory waste.
- The list:
- The time to find and insert increases with each element;
- Occupies small space, wastes little memory.
set
A set, like a dict, is a set of keys, but does not store values. Because the key cannot be repeated, there is no duplicate key in set. To create a set, supply a list as the input set:
> > > s = set ([1, 1, 2, 2, 3, 3]) > > > s {1, 2, 3} # repeating element in the set automatically filteredCopy the code
- through
add(key)
The set () method can add elements to a set, which can be added repeatedly but has no effect:
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
Copy the code
- through
remove(key)
Method to delete elements:
>>> s.remove(4)
>>> s
{1, 2, 3}
Copy the code
- A set can be thought of as a mathematical set of unordered and non-repeating elements. Therefore, two sets can be done mathematically
Intersection | &, and set
Operations such as:
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}
Copy the code
function
Call a function
- abs(-1) >>> 1
- Max (5,4,6,1) > > > 6
- int(‘123’) >>> 123
- str(123) >>> ‘123’
Define the function def
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-99))
99
Copy the code
- An empty function
pass
Def nop(): pass # pass can be used as a placeholder, for example, if you haven't decided how to write the function code, you can put a pass in it to make the code work.Copy the code
- The parameter checking
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
TypeError: bad operand type
Copy the code
- Return multiple values
The # import Math statement imports the Math package and allows subsequent code to reference the sin, cos, and other functions in the Math package. import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny >>> x, y = move(100, 100, 60, Math.pi / 6) >>> print(x, y) 151.96152422706632 70.0 # >>> r = move(100, 100, 60, math.pi / 6) >>> print(r)Copy the code
Parameters of a function
The default parameters
- def power(x,
n=2
), n defaults to 2, i.e. power(5) is equivalent to power(5, 2).
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
Copy the code
- Note:
- Mandatory parameters come before default parameters
- When a function has more than one argument, place the argument that changes a lot first and the argument that changes a little later.
Parameters that change little can be used as default parameters
. Reduces the difficulty of calling a function.
- One thing to keep in mind when defining default parameters is that default parameters must
Pointing to immutable object
!
Variable parameter
*
numbers
def calc(*numbers): sum = 0 for n in numbers: Sum = sum + n * n return sum >>> calc(1, 2) 5 >>> calc() 0 To call a variable argument >>> nums = [1, 2, 3] >>> calc(*nums) 14Copy the code
- *nums means that all elements of the nums list are passed in as variables.
Keyword parameter
Mutable arguments allow you to pass in zero or any arguments that are automatically assembled into a tuple when the function is called. Keyword arguments, on the other hand, allow you to pass in zero or any arguments with parameter names, which are automatically assembled into a dict inside the function. Take an example:
Def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) When calling this function, you can pass only the required arguments: >>> Person ('Michael', 30) Name: Michael age: 30 other: Person ('Bob', 35, city='Beijing') name: Bob age: 35 Other: {'city': 'Beijing'} >>> person('Adam', 45, gender='M', job='Engineer') name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}Copy the code
-
Application: Imagine that you are creating a user registration function, except username and age are mandatory, all the other options are optional, using the keyword parameter to define this function to meet the registration requirements.
-
Like mutable arguments, you can assemble a dict and pass it as a keyword argument:
-
**extra means to pass all the key-values of the dict extra into the **kw parameter, and kw will get a dict. Note that the dict obtained by KW is a copy of extra, and changes to KW will not affect the extra.
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
Copy the code
Name keyword arguments
- If you want to
The name of the restricted keyword argument
, you can use named keyword arguments, for example, accept only city and job as keyword arguments. The function defined in this way is as follows: - * The following arguments are treated as named keyword arguments.
def person(name, age, *, city, job):
print(name, age, city, job)
>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
Copy the code
- If the function definition already has a mutable argument, the following named keyword argument does not need a special delimiter * :
def person(name, age, *args, city, job):
print(name, age, args, city, job)
Copy the code
- Named keyword arguments must be passed in parameter names, unlike positional arguments. If no parameter name is passed, the call will report an error:
>>> person('Jack', 24, 'Beijing', 'Engineer') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Person () takes 2 positional arguments but 4 were given But the person() function takes only two positional arguments.Copy the code
- The named keyword argument can have
The default value
, thus simplifying the call:
def person(name, age, *, city='Beijing', job):
print(name, age, city, job)
Copy the code
- Due to named keyword arguments
City has a default value
, without passing in the city argument:
>>> person('Jack', 24, job='Engineer')
Jack 24 Beijing Engineer
Copy the code
- When using named keyword arguments, be careful if
No variable parameters
, it is necessary toAdd an * as a special separator
. Without *, the Python interpreter will not recognize positional arguments and named keyword arguments:
Parameter combination
- The parameters must be defined in the following order: Mandatory, default, variable, named keyword, and keyword parameters.
def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) >>> f1(1, 2) a = 1 b = 2 c = 0 args = () kw = {} >>> f1(1, 2, c=3) a = 1 b = 2 c = 3 args = () kw = {} >>> f1(1, 2, 3, 'a', 'b') a = 1 b = 2 c = 3 args = ('a', 'b') kw = {} >>> f1(1, 2, 3, 'a', 'b', x=99) a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99} >>> f2(1, 2, d=99, ext=None) a = 1 b = 2 c = 0 d = 99 kw = {'ext': >>> args = (1, 2, 3, 4) >>> kw = {'d': 99, 'x': '#'} >>> f1(*args, **kw) a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'} >>> args = (1, 2, 3) >>> kw = {'d': 88, 'x': '#'} >>> f2(*args, **kw) a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}Copy the code
section
The default parameters
Be sure to use immutable objects, if it is mutable, the program will run logic errors!*args
Is a mutable parameter, and arGS receives onetuple
(a);- Mutable arguments can be passed either directly to func(1, 2, 3) or by assembling a list or tupleArgs passed: func((1, 2, 3));
**kw
Is a keyword argument, kw receives onedict
{}.- Keyword arguments can either be passed directly to: func(a=1, b=2) or dict can be assembled and passed through kw to: func({‘a’: 1, ‘b’: 2}).
- Define named keyword arguments and don’t forget to write delimiters if there are no mutable arguments
*
Otherwise, positional parameters will be defined.
Recursive function
A function is recursive if it calls itself internally. For example, let’s calculate the factorial n factorial. = 1 x 2 x 3 x … X n, expressed by the function fact(n) :
def fact(n): if n==1: return 1 return n * fact(n - 1) ===> fact(5) ===> 5 * fact(4) ===> 5 * (4 * fact(3)) ===> 5 * (4 * (3 * fact(2))) ===> 5 * (4 * (3 * (2 * fact(1)))) ===> 5 * (4 * (3 * (2 * 1))) ===> 5 * (4 * (3 * 2)) ===> 5 * (4 * 6) ===> 5 * 24 ===> 120Copy the code
Preventing stack overflow
- The advantage of using recursive functions is that the logic is simple and clear, but the disadvantage is that too deep a call will cause stack overflow.
- The solution to recursive call stack overflow is through
Tail recursion
Optimization, tail recursion is actually the same as loop, so it’s ok to think of loop as a special tail recursion function.
Tail-recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize tail recursion so that the recursion itself takes up only one stack frame no matter how many times it is called, and no stack overflow occurs.
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
# fact(5)的调用过程
===> fact_iter(5, 1)
===> fact_iter(4, 5)
===> fact_iter(3, 20)
===> fact_iter(2, 60)
===> fact_iter(1, 120)
===> 120
Copy the code
- The standard Python interpreter is not optimized for tail recursion, and any recursive function has stack overflow problems.
Advanced features
slice
The list slice
Taking part of a list or tuple is a very common operation. For example, a list would look like this: L = [‘Michael’, ‘Sarah’, ‘Tracy’, ‘Bob’, ‘Jack’]. If I take the first three elements, what do I do?
L[0:3]
Indicates that the value starts at index 0 and ends at index 3, excluding index 3. The index0,1,2
That’s exactly 3 elements.
>>> L[0:3]
['Michael', 'Sarah', 'Tracy']
Copy the code
- If the first index is 0, we can omit it:
>>> L[:3]
['Michael', 'Sarah', 'Tracy']
Copy the code
- Similarly, since Python supports it
L[-1]
Take the reciprocal first element, then it also supports reciprocal slices
>>> L[-2:]
['Bob', 'Jack']
>>> L[-2:-1]
['Bob']
Copy the code
- Slicing is very useful. Let’s create a sequence from 0 to 99:
> > > L = list (range (100)) > > > L [0, 1, 2, 3,..., 99] before the # 11-20 number: >>> L[10:20] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> L[:10:2] >>> L[::5] [0, 5, 10, 15, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] >>> L[:] [0, 1, 2, 3, ..., 99]Copy the code
The tuple slice
tuple
It’s also a list, the only difference being that tuples are immutable. Therefore, a tuple can also be sliced, but the result of the operation is still a tuple:
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
Copy the code
String slice
- The string ‘XXX’ can also be thought of as a kind of list, where each element is a single character. Therefore, strings can also be sliced, but the result is still a string:
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'
Copy the code
The iteration
Given a list or tuple, we can iterate through the list or tuple through the for loop, which we call Iteration. In Python, iteration is done through for… To accomplish:
list
for (i=0; i<list.length; i++) {
n = list[i];
}
Copy the code
dict
- List does have indices, but many other data types don’t have indices, but as long as you’re iterable,
We can iterate with or without subscripts
Dict, for example, iterates:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
... print(key)
...
a
c
b
Copy the code
The default
In this case, dict iterates overkey
. If I want to iteratevalue
, you can usefor value in d.values()
, if you want to iterate simultaneouslyThe key and the value
, you can usefor k, v in d.items()
.
string
- Since strings are also iterable, we can also apply them to the for loop:
>>> for ch in 'ABC':
... print(ch)
...
A
B
C
Copy the code
Determine that an object is an iterable
- Judging from the Iterable type of the Collections module:
>>> from collections import Iterable >>> isinstance(' ABC ', Iterable) # STR Iterable True >>> isinstance([1,2,3], Iterable) # list Iterable True >>> isinstance(123, Iterable) # Iterable FalseCopy the code
enumerate
Index-element pairs
- The Python built-in
enumerate
The function can change a list toIndex-element pairs
, so we can iterate over both the index and the element itself in the for loop:
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
Copy the code
- In the for loop above, at the same time
Two variables are referenced
Is common in Python, such as the following code:
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... One, one, two, four, three, nineCopy the code
List generator
List Comprehensions are a simple yet powerful Python generator that can be used to create lists.
Create list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > > list (range (1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # generate [1 x1, x2, 2 3 x3,..., 10 x10] > > > [x x x for x in range (1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] > > > [m + n the for m 'ABC' in the for n 'XYZ'] in [' AX ', 'AY,' ' ', 'BX', 'BY' and 'BZ', 'CX', 'CY', 'CZ] # to list the files and directories of the current directory name, This can be done with one line of code: >>> import OS >>> [d for d in os.listdir('.')] # os.listdir can list files and directories ['.emacs.d', '.ssh', '.trash ', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']Copy the code
- The for loop can actually be used simultaneously
Two or more variables
, such asDict items ()
We can iterate over key and value simultaneously:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
... print(k, '=', v)
...
y = B
x = A
z = C
Copy the code
- A list generator can also use two variables to generate a list:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
Copy the code
- Change all the strings in a list to
lowercase
:
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
Copy the code
if… else
>>> [x for x in range(1, 11) if x % 2 == 0]
[2, 4, 6, 8, 10]
Copy the code
- However, we
Can't
At the end, if pluselse
If followed by for is a filter condition, can not have else, otherwise how to filter?
>>> [x for x in range(1, 11) if x % 2 == 0 else 0]
File "<stdin>", line 1
[x for x in range(1, 11) if x % 2 == 0 else 0]
^
SyntaxError: invalid syntax
Copy the code
- the
Write if before for
We have to add else, because the first part of for is an expression, and it has to compute a result based on x. So, look at the expression: x if x % 2 == 0, it cannot compute from x because else is missing, else must be added:
>>> [x if x % 2 == 0 else -x for x in range(1, 11)] [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10] # if x % 2 == 0 else -x % 2 == 0 elseCopy the code
- In a list generator,
For the front
theif ... else
Is the expression, andFor the back
If of is the filter condition,Can't take the else
.
The generator
In Python, the mechanism for calculating while looping is called a generator.
Create Method 1
- Simply change a list generator [] to () to create a generator:
- The only difference between creating L and g is the outermost [] and (), where L is a list and g is a generator.
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
Copy the code
- If you want to print them out one by one, use the for loop, since generator is also iterable:
>>> g = (x * x for x in range(10)) >>> for n in g: ... print(n) ... 0 1 49 16 25 36 49 64 81Copy the code
Creation Method 2
Change print(b) to yield b. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>
Copy the code
The execution flow of generator and function is different. Functions are executed sequentially, returning when they encounter a return statement or the last line of function statements. Functions that become generators, on the other hand, execute each time next() is called, return from a yield statement, and continue execution from the last yield statement when executed again.
- For a simple example, define a generator that returns the numbers 1, 3, and 5:
def odd(): Print ('step 2') yield(3) print('step 3') yield(5) Then use the next() function to keep getting the next return value: >>> o = odd() >>> next(o) step 1 1 >>> next(o) step 2 3 >>> next(o) step 3 5 >>> next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIterationCopy the code
summary
- To understand how the generator works, it is in
for
The loop continuously evaluates the next element and ends the for loop under appropriate conditions. For a generator, a return statement or the last line of the function is an instruction to terminate the generator, and the for loop ends. - Note the distinction between regular functions and generator functions. Regular function calls return results directly:
>>> r = abs(6)
>>> r
6
Copy the code
- A “call” to the generator function actually returns a generator object:
>>> g = fib(6)
>>> g
<generator object fib at 0x1022ef948>
Copy the code
The iterator
Functional programming
Higher-order functions
Variables can point to functions.
>>> f = abs >>> f(-10) 10 # Indicates that the variable f now refers to the abs function itself. Calling abs() directly is exactly the same as calling the variable f().Copy the code
Function names are also variables
For abs(), you can treat abs as a variable that points to a function that evaluates the absolute value!
>>> abs = 10 >>> abs(-10) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable # abs(-10) Because the abs variable is no longer pointing to the absolute value function but to the integer 10!Copy the code
- Note: Since the ABS function is actually defined in the import Builtins module, to change the reference of the ABS variable to take effect in other modules, use import Builtins; Builtins. Abs = 10.
The incoming function
A function that can take another function as an argument is called a higher-order function. One of the simplest higher-order functions:
def add(x, y, f): F (x) + f(y) ==> ABS (-5) + abs(6) ==> 11 return 11Copy the code
map/reduce
map()
The map() function takes two arguments, a function and an Iterable. Map applies the passed function to each element of the sequence in turn and returns the result as a new Iterator.
F (x)=x (x); f(x)=x (x); f(x)=x (x); f(x)=x (x);
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Copy the code
- The first argument passed to map() is f, the function object itself. Since the result r is an Iterator, and the Iterator is an inert sequence, it passes
list()
The function evaluates the entire sequence and returns a list.
As a higher-order function, map() actually abstracts the rules of operation, so we can compute not only simple f(x)=x2, but also arbitrarily complex functions, such as converting all the numbers in the list to strings:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Copy the code
reduce()
Reduce applies a function to a sequence [x1, x2, x3… The function must take two arguments, reduce continues the result with the next element of the sequence, resulting in:
Copy the code
- For example, summing over a sequence can be implemented using reduce:
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
Copy the code
- Of course, you can use the Python built-in sum() function directly instead of reduce.
- But if you want to convert the sequence [1, 3, 5, 7, 9] to the integer 13579, reduce can come in handy:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
Copy the code
- The function that converts STR to int:
>>> from functools import reduce
>>> def fn(x, y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... return digits[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579
Copy the code
- Organize into a
str2int
The function of is:
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
Copy the code
fliter
Filter () also receives a function and a sequence. Unlike map(), filter() applies the passed function to each element in turn, and then decides whether to keep or discard the element depending on whether the value returned is True or False.
- For example, in a list, if you delete the even numbers and keep only the odd numbers, you might write:
Def is_odd(n): return is_odd(1, 2, 4, 5, 6, 9, 10, 15))Copy the code
- To delete an empty string from a sequence, write:
Def not_empty (s) : return s and s.s trip () list (filter (not_empty, [' A ', ', 'B', None, 'C', '])) # results: [' A ', 'B', 'C']Copy the code
Note:
The filter() function returns oneIterator
, is an inert sequence, so to force filter() to complete the calculation, you need to uselist()
The function gets all the results and returns the list.
sorted
Python’s built-in sorted() function sorts lists:
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
Copy the code
- The sorted() function is also a higher-order function that can also accept a key function for custom sorting, such as sorting by absolute size:
>>> sorted([36, 5, -12, 9, -21, key=abs) [5, 9, -12, -21, 36] Keys sorting result = > [5, 9, 12, 21, 36] | | | | | end result = > [5, 9, and 12-21, 36]Copy the code
Returns the function
Function as the return value
In addition to accepting functions as arguments, higher-order functions can also return functions as result values.
- Let’s implement a sum of variable arguments. In general, the summation function is defined as follows:
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
Copy the code
- But what if you don’t need to sum it right away, but later in the code, calculate it as needed? Instead of returning the result of the summation, we can return the summation function:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
Copy the code
- When we call
lazy_sum()
Instead of returning the summation result, the summation function is returned:
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function lazy_sum.<locals>.sum at 0x101c6ed90>
Copy the code
- The result of the summation is actually computed when f is called:
>>> f()
25
Copy the code
In this example, we define sum in the function lazy_sum, and sum can refer to the arguments and local variables of lazy_sum. When lazy_sum returns sum, the parameters and variables are stored in the returned function. This program structure, called closures, is powerful.
Pay attention to
When we call lazy_sum(), each call returns a new function, even if the same argument is passed:
> > > f1 = lazy_sum (1, 3, 5, 7, 9) > > > f2 = lazy_sum (1, 3, 5, 7, 9) > > > = = f1 f2 False # f1 and f2 () () call result each other.Copy the code
closure
The returned function refers to the local variable args inside its definition, so when a function returns a function, its internal local variable is also referred to by the new function. Therefore, closure is simple to use but not easy to implement.
def count(): fs = [] for i in range(1, 4): def f(): Return I * I fs.append(f) return fs f1, f2, f3 = count() # in the above example, a new function is created each time, and then all three functions are returned. >>> f1() 9 >>> f2() 9 >>> f3() 9Copy the code
- All of them are
9
! The reason is that the returned function references variablesi
But it is not implemented immediately. By the time all three functions return, the variable I referenced by them has changed to 3, so the final result is 9. - When the closure is returned
Keep in mind
One point: return functionDon't
Reference any loop variable, or variable that will change later. - If we must refer to a loop variable, we do this by creating a new function that binds the current value of the loop variable with its arguments. The values that are bound to the function parameter remain unchanged, regardless of subsequent changes to the loop variable:
def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): Fs. Append (f (I)) # f (I) is executed immediately, so I passed the current value of f () return the fs > > > f1, f2, f3 = the count () > > > formula one (1) > > > f2 (4) > > > f3 () 9Copy the code
Anonymous functions
In Python, there is limited support for anonymous functions. If f(x)=x^2, you can pass in an anonymous function: f(x)=x^2
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) [1, 4, 9, 16, 25, 36, 49, 64, 81] Def f(x): return x * xCopy the code
- The keyword
lambda
Represents an anonymous function, before the colonx
Represents function parameters. - Anonymous functions have a limitation, that is, they can only have one expression
return
The return value is the result of the expression.
Decorator
Since a function is also an object and a function object can be assigned to a variable, it can also be called from a variable.
>>> def now():
... print('2015-3-25')
...
>>> f = now
>>> f()
2015-3-25
Copy the code
- The function object has a __name__ attribute that takes the name of the function:
>>> now.__name__
'now'
>>> f.__name__
'now'
Copy the code
Suppose we want to enhance the now() function by, for example, automatically printing logs before and after a function call, but we don’t want to change the definition of the now() function. This way of dynamically adding functionality while the code is running is called a Decorator.
- In essence, a decorator is a higher-order function that returns a function. So, we need to define a decorator that prints logs as follows:
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
Copy the code
Partial functions
When we introduced function arguments, we said that function calls can be made easier by setting default values for the parameters. And partial functions can do the same thing. Examples are as follows:
int()
The int() function converts a string to an integer. When only a string is passed in, the int() function converts to decimal by default:
>>> int('12345')
12345
Copy the code
- But the int() function provides something extra
base
Parameter, the default value is10
. If we pass in the base argument, we can do the n-base conversion:
>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565
Copy the code
- Suppose you want to convert a large number of binary strings, passed in each time
int(x, base=2)
It’s a lot of trouble, so we thought, well, we can define oneint2()
Function, defaultbase=2
Passed in:
def int2(x, base=2):
return int(x, base)
>>> int2('1000000')
64
>>> int2('1010101')
85
Copy the code
functools.partial
Int2 () is what helps us to create a partial function. Instead of defining int2(), we can create a new function using the following codeint2
:
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
Copy the code
- Functools. partial is used to assign certain parameters to a function
Hold the
(that is, setting the default value), returns a new function that will be easier to call. - When you create a partial function, it actually accepts
The function object
,*args
andkw
These three parameters.
The module
Use the module
Object-oriented programming Class
- Data encapsulation, inheritance and polymorphism are three main features of object orientation
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
Copy the code
Classes and Instances
In Python, classes are defined using the class keyword:
class Student(object):
pass
Copy the code
Class is followed by the class name, Student, which is usually an uppercase word, followed by (object), which indicates the class from which it inherits. Usually, if there is no suitable inheriting class, the object class is used, which is what all classes eventually inherit.
Class +(); class +(); class +();
>>> bart = Student() >>> bart <__main__.Student object at 0x10a67a590> >>> Student <class '__main__.Student'> # The variable bart points to an instance of Student, followed by 0x10a67a590, which is the memory address. Each object has a different address, and Student is a class.Copy the code
- You can freely bind attributes to an instance variable, for example, to
Instance bart
Bind aThe name attribute
:
>>> bart.name = 'Bart Simpson'
>>> bart.name
'Bart Simpson'
Copy the code