Introduction to Python (5) Definition of Functions

The definition of a function in python
starts with def, followed by the name of the function definition and ()) 'parameters defined in parentheses' start with a colon, and scale, and return ends
as:

 def  hello (ming):
         print ming
         return 

Pass parameters:

ming=[1,2,3]
ming="ok"
As shown above, the variable has no type. It can be a list or a str
parameter.

必备参数
关键字参数
默认参数
不定长参数

Required parameters:

 def  hello (ming):
         print ming
         return 

调用函数
hello();

then it will give an error

Keyword arguments:

 def  hello (ming):
         print ming
         return 

调用函数
hello(ming="ok");

output is ok

Default function:

 def  hello (n,m=10):
         print n
         print m

调用函数
hello(n=20,m=20);
hello(n=100

Return value
n=20 m=20
n=100 m=10
Variable length parameters:

 def  hello (*args):
         print args
         return 

调用函数
hello(1);
hello(1,2,3,4)

Output
1
1,2,3,4
anonymous function:

正常函数:
 def  hello (n,m):
         print n*m
匿名函数:
lambda n,m:n*m

Multiple parameters:

 def  hello (a,*args,**kwargs):
         print args
         return 

调用函数
hello(1,2,3,4,n=1,m=2)

Output:
1
(2,3,4)
{n:1,m:2}
Higher order function:

map是计算乘积的高阶函数
def hello(x):
    print x * x

map(hello,[1,2,3,4])
输出相同:
1,4,9,16
reduce是计算累计的高阶函数
def hi (x,y):
    print x+y
reduce(hi,[1,2,3,4])
    输出同样一样:
15

SORTED sorting is more commonly used in higher-order functions

n = [5,7,6,3,4,1,2]
 m = sorted(n)      
print n
[5, 7, 6, 3, 4, 1, 2]
 print m
[1, 2, 3, 4, 5, 6, 7]
 A=dict(a=1,c=2,b=3,d=4)
如果我们直接排序
print(sorted(A))
['a', 'b', 'c', 'd']
 print(sorted(A.item(), key=lambda x:x[1]) )           
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
按倒叙排序
 print(sorted(A.item(), key=lambda x:x[1],reverse=True) )    
 [('d', 4), ('b', 3), ('c', 2), ('a', 1)]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324486702&siteId=291194637