像这种内层函数引用了外层函数的变量(参数也算变量),然后返回内层函数的情况,称为闭包(Closure)。
闭包的特点是返回的函数还引用了外层函数的局部变量,所以,要正确使用闭包,就要确保引用的局部变量在函数返回后不能变。
闭包的特点是返回的函数还引用了外层函数的局部变量,所以,要正确使用闭包,就要确保引用的局部变量在函数返回后不能变。
2018-09-17
def format_name(s):
return s.capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
return s.capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
2018-09-15
def count():
fs = []
def f():
for i in range(1,4):
s=i*i
fs.append(s)
print s
return fs
return f
fs = count()
print fs()
fs = []
def f():
for i in range(1,4):
s=i*i
fs.append(s)
print s
return fs
return f
fs = count()
print fs()
2018-09-15
def multi(x,y):
return x*y
def calc_prod(f,lst):
def calcs():
return reduce(f,lst)
return calcs
f = calc_prod(multi,[1, 2, 3, 4])
print f()
return x*y
def calc_prod(f,lst):
def calcs():
return reduce(f,lst)
return calcs
f = calc_prod(multi,[1, 2, 3, 4])
print f()
2018-09-15
sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序,比较函数的定义是,传入两个待比较的元素 x, y
2018-09-11
def num(q):
n=[]
def x(q):
q=q+1
for i in range(1,q):
n.append(i*i)
str_convert = ' '.join(list(map(str,n)))
return str_convert
return x(q)
print num(3)
n=[]
def x(q):
q=q+1
for i in range(1,q):
n.append(i*i)
str_convert = ' '.join(list(map(str,n)))
return str_convert
return x(q)
print num(3)
2018-09-10
def cmp_ignore_case(s1, s2):
if s1[0].upper() < s2[0].upper():
return -1
if s1[0].upper() > s2[0].upper():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
if s1[0].upper() < s2[0].upper():
return -1
if s1[0].upper() > s2[0].upper():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2018-09-10
import math
def is_sqr(x):
return math.sqrt(x) - int(math.sqrt(x)) == 0
print filter(is_sqr,list(range(1, 101)))
def is_sqr(x):
return math.sqrt(x) - int(math.sqrt(x)) == 0
print filter(is_sqr,list(range(1, 101)))
2018-09-10
class Person(object):
pass
p1 = Person()
p1.name = 'Bart'
p2 = Person()
p2.name = 'Adam'
p3 = Person()
p3.name = 'Lisa'
L1 = [p1,p2,p3]
L2 = [];
for i in L1:
L2.append(i.name)
L3 = sorted(L2)
print(L3)
表示lambda函数不太理解
pass
p1 = Person()
p1.name = 'Bart'
p2 = Person()
p2.name = 'Adam'
p3 = Person()
p3.name = 'Lisa'
L1 = [p1,p2,p3]
L2 = [];
for i in L1:
L2.append(i.name)
L3 = sorted(L2)
print(L3)
表示lambda函数不太理解
2018-09-10
def format_name(s):
return s[0].upper()+s[1:].lower()
print map(format_name, ['adam', 'LISA', 'barT'])
return s[0].upper()+s[1:].lower()
print map(format_name, ['adam', 'LISA', 'barT'])
2018-09-04
def __init__(self, num):
self.num = num
self.fibo = [0]
self.a,self.b = 0,1
for x in range(num-1):
self.a , self.b = self.b , self.a + self.b
self.fibo.append(self.a)
self.num = num
self.fibo = [0]
self.a,self.b = 0,1
for x in range(num-1):
self.a , self.b = self.b , self.a + self.b
self.fibo.append(self.a)
2018-08-29