python基础-- 06 函数

1.查看函数帮助

         help(函数)

2.函数

2.1使用举例

>>> def square_of_sum(L):

...    sum=0

...    for i in L:

...             sum+=i

...    return sum

...

>>> print square_of_sum([1,2,3,4,5])

15

2.2注意

return None等同于不写return

多返回值的方法返回值其实是元组

2.3递归函数

2.3.1定义

       如果一个函数在内部调用自身本身,这个函数就是递归函数

2.3.2举例

>>> def fact(n):

...    if n==1:

...           return 1

...    return n*fact(n-1)

...

>>> fact(6)

720

2.3.3栈溢出

       使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。可以试试计算 fact(10000)。

2.3.4汉诺塔

# 汉诺塔函数

# 参数:

#     n--初始柱子上有多少个圆盘

#     from_place--初始柱子编号

#     tmp_place--中间柱子编号

#     to_place--目标柱子编号

# 返回值:

#     无

def move_yc(n,from_place,tmp_place,to_place):

   

    # 结束递归

    if n ==1:

        print "move", n,"in",from_place,"to",to_place

        #print from_place,'-->',to_place

        return

   

    # 把from_place上的上面n-1个挪到tmp_place上

    move_yc(n-1,from_place,to_place,tmp_place)

   

    # 把from_place上的最下面的1个挪到to_place上

    print "move", n,"in",from_place,"to",to_place

    #print from_place,'-->',to_place

   

    # 把tmp_place上的全部挪到to_place上

    move_yc(n-1,tmp_place,from_place,to_place)

       结果:

       

2.4函数的形参、实参

2.4.1注意

       由于函数的参数按从左到右的顺序匹配,所以默认参数只能定义在必需参数的后面。

       默认参数值的获取是在定义时刻,函数内变量的获取是在运行时刻

2.4.2举例

请定义一个 greet() 函数,它包含一个默认参数,如果没有传入,打印 'Hello, world.',如果传入,打印 'Hello, xxx.'

def greet(des='world'):

    print "Hello,",des+"."

2.4.3知识点

形参 - 定义函数时候的参数

实参 - 调用函数时的参数

实参用关键字+等号时不用按照顺序;

形参用关键字+等号时表示默认值

2.5可变参数

2.5.1概念

一个函数能接受任意个参数

2.5.2实现

可变参数的名字前面有个*号,我们可以传入0个、1个或多个参数给可变参数,Python解释器会把传入的一组参数组装成一个tuple传递给可变参数,因此,在函数内部,直接把变量args看成一个tuple就好了

2.5.3举例

请编写接受可变参数的 average() 函数,可以计算任意个数的平均值

def average(*args):

    sum=0.0

    n=0

    for tmp in args:

        n+=1

        sum +=tmp

    if n==0:

        return 0.0

    return sum/n

2.6*args和**kw的区别

*是包含其他单元素类型的参数的,在这里面args是一个tuple

**是包含的是xx=xx类型的参数,在这里面kw是一个dict

两者顺序不可放反!!

>>> def test_method(a,b,*args,**kw):

         print a

         print b

         print args

         print kw

 

>>> test_method(1,2,3,4,5,key="ddd")

1

2

(3, 4, 5)

{'key': 'ddd'}

>>> test_method(1,2,3,4,5,key="ddd",name="zhangsan")

1

2

(3, 4, 5)

{'name': 'zhangsan', 'key': 'ddd'}

>>> test_method(1,2,3,4,5,key="ddd",6,name="zhangsan")

SyntaxError: non-keyword arg after keyword arg

http://www.cnblogs.com/ShawnYuki/p/6932658.html

2.7获取函数名__name__

>>> abs.__name__

'abs'

2.8获取函数的所有特殊方法

>>> dir(abs)

['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

3.其他函数

3.1 字符串相关

3.1.1 strip()函数

s.strip(rm) 删除 s 字符串中开头、结尾处的 指定字符

当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')

>>> a='     123'

>>> a.strip()

'123'

>>> a

'     123'

>>> a='\t\t123\r\n'

>>> a

'\t\t123\r\n'

>>> a.strip()

'123'

3.1.2 upper()函数和lower()函数

upper() 方法可以返回大写的字母

lower() 方法可以返回小写的字母

3.2 一个iter相关

3.2.1 len(object)

len()函数可以计算任意可迭代对象的大小

3.2.2 join函数

join()方法可以以指定分隔符把一个可迭代的对象以(“元素1”+“分隔符”+“元素2”...)拼接成一个字符串

语法:  'sep'.join(seq)

参数说明

       sep:分隔符。可以为空

       seq:要连接的元素序列、字符串、元组、字典

       上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

 

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

>>> "+".join(['1','2','3','4'])

'1+2+3+4'

3.2.3 map()函数

map()是 Python 内置的高阶函数,它接收一个函数 f和一个list,并对list的每个元素调用f函数,得到一个新的 list 并返回。

>>> def f(x):

...    return x*x

...

>>> map(f,[1,2,3,4,5,6,7])

[1, 4, 9, 16, 25, 36, 49]

3.2.4 filter()函数

filter()函数接收一个函数 f和一个list,这个函数f是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list

>>> def is_odd(x):

...    return x%2==1

...

>>> filter(is_odd,[1,2,3,4,5,6])

[1, 3, 5]

3.2.5 sorted()函数

对可迭代对象进行排序,可自定义排序方法

sorted(...)

    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

注:cmp处为处理函数,key为指定比较内容的函数

注:python3中去掉了cmp,只使用key与reverse

  key的函数体内元组代表使用元组内从后往前的所有比较项来进行比较。即进行len(元组)次比较。

  元组越靠前的项目占得权重越大,因为越靠前,越最后才进行比较。

  点击查看key的原理

p1 = Person()

p1.name = 'Bart'

 

p2 = Person()

p2.name = 'Adam'

 

p3 = Person()

p3.name = 'Lisa'

 

L1 = [p1, p2, p3]

def compare_ignore_case(s1,s2):

    if s1[:1].lower()>s2[:1].lower():

        return 1

    if s1[:1].lower()<s2[:1].lower():

        return -1

    return 0

L2 = sorted(L1,cmp=compare_ignore_case,key=lambda x:x.name)

3.2.6 reduce()函数

从左到右将累积两个参数的函数应用于序列的项目,以将序列减少为单个值。

reduce(function, sequence[, initial]) -> value

>>> reduce(f,[1,3,5,7,9])

x->1,y->3

x->4,y->5

x->9,y->7

x->16,y->9

25

reduce()还可以接收第3个可选参数,作为计算的初始值

>>> reduce(f,[1,3,5,7,9],100)

x->100,y->1

x->101,y->3

x->104,y->5

x->109,y->7

x->116,y->9

125

注:python3中,要使用reduce,得从functools中引入,加上:from functools import reduce才能够用。

3.3 两个iter相关

3.3.1 zip函数

zip()函数可以把两个list变成一个list

>>> zip([10,20,30],['A','B','C'])

[(10, 'A'), (20, 'B'), (30, 'C')]

>>> zip([10,20,30],['A','B','C','D'])

[(10, 'A'), (20, 'B'), (30, 'C')]

3.4 其他

3.4.1 isinstance()函数

isinstance(object, class-or-type-or-tuple) 可以判断变量 x 是否为某类型

>>> help(isinstance)

Help on built-in function isinstance in module __builtin__:

 

isinstance(...)

    isinstance(object, class-or-type-or-tuple) -> bool

   

    Return whether an object is an instance of a class or of a subclass thereof.

    With a type as second argument, return whether that is the object's type.

    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for

    isinstance(x, A) or isinstance(x, B) or ... (etc.).

3.4.2 type() 函数

获取变量的类型,它返回一个 Type 对象:

>>> type(123)

<type 'int'>

>>> s = Student('Bob', 'Male', 88)

>>> type(s)

<class '__main__.Student'>

3.4.3 dir() 函数

获取变量的所有属性。

dir()返回所有实例属性,包括`__class__`这类有特殊意义的属性。

方法也是对象的一个属性。

可以使用dir()函数配合filter函数去掉特殊变量“__xx__”(print filter(lambda attr:attr[:2]!='__',dir(p)))

>>> dir(123)   # 整数也有很多属性...

['__abs__', '__add__', '__and__', '__class__', '__cmp__', ...]

>>> dir(s)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'gender', 'name', 'score', 'whoAmI']

 

posted @ 2017-10-29 00:38  yc紫日  阅读(207)  评论(0编辑  收藏  举报