有的同学不是很明白生成顺序
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j*j
return g
r=f(i)
fs.append(r)
return fs
for name in count():
print name()
就明白了
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j*j
return g
r=f(i)
fs.append(r)
return fs
for name in count():
print name()
就明白了
2018-06-13
def calc_prod(lst):
def lazy_prod():
return reduce(lambda x, y: x * y, lst)
return lazy_prod
pass
def lazy_prod():
return reduce(lambda x, y: x * y, lst)
return lazy_prod
pass
2018-06-12
def f(lst):
def g():
def mul(x, y):
return x*y
return reduce(mul,lst)
return g
lst = [2, 3, 4, 5]
a = f(lst)
print(a())
def g():
def mul(x, y):
return x*y
return reduce(mul,lst)
return g
lst = [2, 3, 4, 5]
a = f(lst)
print(a())
2018-06-12
python3中已经用不了上面的方法了,我用这种方法排序:
>>> my_list = ['bob', 'about', 'Zoo', 'Credit']
>>> sorted(my_list, key=lambda x: x.lower())
['about', 'bob', 'Credit', 'Zoo']
>>> my_list = ['bob', 'about', 'Zoo', 'Credit']
>>> sorted(my_list, key=lambda x: x.lower())
['about', 'bob', 'Credit', 'Zoo']
2018-06-12
def f_cmp(x,y):
if x[:1].lower() < y[:1].lower():
return -1
if x[:1].lower() > y[:1].lower():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'],f_cmp)
if x[:1].lower() < y[:1].lower():
return -1
if x[:1].lower() > y[:1].lower():
return 1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'],f_cmp)
2018-06-09
用辗转相除法求最大公约数:
def function(a,b):
c=a%b
if c==0:
return b
if c!=0:
a,b=b,c
return function(a,b)
def function(a,b):
c=a%b
if c==0:
return b
if c!=0:
a,b=b,c
return function(a,b)
2018-06-08
import math
def is_sqr(x):
if math.sqrt(x) in range(1,11):
return x
else:
return None
print filter(is_sqr, range(1, 101))
def is_sqr(x):
if math.sqrt(x) in range(1,11):
return x
else:
return None
print filter(is_sqr, range(1, 101))
2018-06-07
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-06-07
既然只打印名字,那时间功能我就不写了吧哈哈
import time, functools
def performance(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' %(text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
import time, functools
def performance(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' %(text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
2018-06-05
def performance(unit):
def qq(f):
def ww(*x):
print '[%s]call %s(),' % (unit, f.__name__)
return f(*x)
return ww
return qq
#其实就是在无参装饰器外面再套一层函数,用于引入一个参数,在python中内层函数可以调用外层的参数,外层的函数不能调用内层的参数
def qq(f):
def ww(*x):
print '[%s]call %s(),' % (unit, f.__name__)
return f(*x)
return ww
return qq
#其实就是在无参装饰器外面再套一层函数,用于引入一个参数,在python中内层函数可以调用外层的参数,外层的函数不能调用内层的参数
2018-06-02