2017-10-29-07内置函数、作用域、闭包、递归

python自带内置函数

abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() import()
complex() hash() min() set()
dict() hex() object() slice()
dir() id() oct() sorted() exec内置表达式
#查看关键字帮助
#由于help(*args,**kwds)需要传入一个参数,关键字(比如:if ,is ,lambda)不能直接传入,需要从关键字列表索引
#查找
>>> from keyword import kwlist
>>> kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> kwlist.index('lambda')
22
>>> help(kwlist[22])
Lambdas
*******

   lambda_expr        ::= "lambda" [parameter_list]: expression
   lambda_expr_nocond ::= "lambda" [parameter_list]: expression_nocond

Lambda expressions (sometimes called lambda forms) are used to create
anonymous functions. The expression "lambda arguments: expression"
yields a function object.  The unnamed object behaves like a function
object defined with:

   def <lambda>(arguments):
       return expression

See section Function definitions for the syntax of parameter lists.
Note that functions created with lambda expressions cannot contain
statements or annotations.

Related help topics: FUNCTIONS


asb(-12)#取绝对值
round(4.4)#四舍五入
round(number[,ndigits])  #(数字,位数)
bin(2)#转换二进制
bin(num,/) #Return the binary representation of an integer.(返回二进制表述)
oct(8)#转换八进制
oct(number,/)#Return the octal representation of an integer.
hex(16)#转换十六进制
hex(number,/)#Return the hexadecimal representation of an integer.
ord('a')#将字符串转换成对应的ASCII码值
ord('A')
chr(65)#将ASCII码值转换成对应的字符
enumerate()函数用于将一个可遍历的数据对象(列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据。
enumerate(iterable[,start])
#enumerate is useful for obtaining an indexed list:
#      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

>>> li=['a','b','c']
>>> list(enumerate(li))
[(0, 'a'), (1, 'b'), (2, 'c')]

#注意  集合、字典是无序的,经过enumerate()枚举之后返回的是(伪索引,value)
>>> di
{'a': 1, 'b': 2}
>>> se
{1, 2, 3, 5, 'abcd'}
>>> list(enumerate(se))
[(0, 1), (1, 2), (2, 3), (3, 5), (4, 'abcd')]
>>> list(enumerate(di))
[(0, 'a'), (1, 'b')]


#filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成filter类
filter(function or None, iterable)

>>> li=['a','b','c']
>>> type(filter(None,li))
<class 'filter'>

>>> def is_odd(n):
	return n%2==1
>>> newlist=filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> print(newlist)
<filter object at 0x0000000002B06FD0>
>>> list(newlist)
[1, 3, 5, 7, 9]

lambda [arg1 [,arg2,...]]:expression #可以用到任何地方

>>> li=[1,2,3,4,5,6,7,8,9,10]
>>> list(filter(lambda x : x >5 ,li))
[6, 7, 8, 9, 10]

#map() 会根据提供的函数对指定序列做映射
map(func,*iterables)—— ——>map object

>>> li
[1, 2, 3, 4, 5, 6, 7, 8]
>>> map(str,li)
<map object at 0x0000000002E497B8>
>>> type(map(str,li))
<class 'map'>
>>> list(map(str,li))#将列表里面的元素转换成字符串了
['1', '2', '3', '4', '5', '6', '7', '8']

#zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
#如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表
zip(iter1 [,iter2 [...]]) --> zip object


>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

变量只是你计算机中存储信息的一部分内存

变量的作用域

'''
当你在函数定义内声明变量的时候,它们与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域。所有变量的作用域是它们被定义的块,从它们名称被定义的那点开始。
'''

>>> a=10  #全局变量
>>> def test1():
	b = 5 #局部变量
	print('局部访问全局变量',a) #局部可以访问全局变量
	a+=1  #局部可以访问全局变量,但是不能修改;如果要修改,需要用global声明
	#注意 global 只对当前函数作用域起效,其他函数没有global声明则不能修改全局变量
    
#全局语句 global    
>>> def test2():
	global a

	print('a is',a)
	a = 2
	print('changed global a to',a)

	
>>> test2()
a is 10
changed global a to 2
>>> print('Value of a is',a)
Value of a is 2

#非局部语句 nonlocal
>>> def test3():
	a = 3
	print('a is',a)
	def test3_inner():
		nonlocal a
		a=5
	
    test3_inner()
	print('changed local a to',a)

	
>>> test3()
a is 3
changed local a to 5
>>> 

闭包

'''
闭包(closure)是函数式编程的重要的语法结构。
必须满足以下几点:

1 必须有一个内嵌函数
2 内嵌函数必须引用外部函数中的变量
3 外部函数的返回值必须是内嵌函数
'''

>>> def stu(name):

	def stu_detail(age):
		print('name',name,'age',age)
	
	return stu_detail

>>> test1 = stu('宇智波佐助')
>>> test1(15)
name 宇智波佐助 age 15
>>> 

递归

'''
例题:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。
       问第4个人岁数,他说比第3个人大2岁。
       问第三个人,又说比第2人大两岁。
       问第2个人,说比第一个人大两岁。
       最后问第一个人,他说是10岁。
       请问第五个人多少岁?
'''
>>> def age(n):
	age=10
	for i in range(1,n+1):  #由于左闭右开,所以这里n+1
		age+=2
		if i ==1:
			age-=2
		print('第 %s 个人, %s 岁' %(i,age))

		
>>> age(5)1 个人, 10 岁
第 2 个人, 12 岁
第 3 个人, 14 岁
第 4 个人, 16 岁
第 5 个人, 18#递归
>>> def age2(n):
	if n==1:
		return 10
	else:
		return age2(n-1)+2

	
>>> age2(5)
18
>>> t1=age2(5-1:
                age2(4-1:
                        age2(3-1:
                                age2(2-1:
                                        age2(1):
                                               return 10  
                                     )+2
                             )+2
                     )+2
            )+2

#例子
#阶乘 1!=1*1  2!=2*1  3!=3*2*1  4!=4*3*2*1  5!=5*4*3*2*1
#     1!      2!=2*1! 3!=3*2!   4!=4*3!     5!=5*4!  

#推导式:    n!=n*(n-1)!
#终止条件:  n == 1  return 1

猜你喜欢

转载自blog.csdn.net/github_38970218/article/details/88543658
今日推荐