最赞回答 / june_fu888
首先是sorted函数,第一个参数为LIST 即 L1 第二个参数为定义的比较函数;lambda p1, p2: cmp(p1.name, p2.name) 意思是,传入p1和p2,比较两者的name这样一分解就容易理解了吧
2015-03-21
import math
def f(x):
if math.sqrt(x) % 1 == 0:
return x
print filter(f, range(1, 101))
def f(x):
if math.sqrt(x) % 1 == 0:
return x
print filter(f, range(1, 101))
2015-03-20
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'])
2015-03-19
from operator import mul
def calc_prod(lst):
def prod():
return reduce(mul, lst, 1)
return prod
f = calc_prod([1, 2, 3, 4])
print f()
def calc_prod(lst):
def prod():
return reduce(mul, lst, 1)
return prod
f = calc_prod([1, 2, 3, 4])
print f()
2015-03-19
import functools
sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
2015-03-19
import time
def performance(unit):
def f1(f):
def f2(n):
t1 = time.time()
r = f(n)
t2 = time.time()
t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
def performance(unit):
def f1(f):
def f2(n):
t1 = time.time()
r = f(n)
t2 = time.time()
t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
2015-03-19
print 'call %s() in %f %s' % (f.__name__, t, unit)
return r
return f2
return f1
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
return r
return f2
return f1
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
2015-03-19
def performance(f):
def log_time(x):
t1= time.time()
r = f(x)
t2=time.time()
print 'call %s() in %fs' % (f.__name__, (t2 - t1))
return r
return log_time
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
def log_time(x):
t1= time.time()
r = f(x)
t2=time.time()
print 'call %s() in %fs' % (f.__name__, (t2 - t1))
return r
return log_time
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
2015-03-19
def count():
fs = []
for i in range(1, 4):
def js(i):
def js1():
return i*i
return js1
a=js(i)
fs.append(a)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
fs = []
for i in range(1, 4):
def js(i):
def js1():
return i*i
return js1
a=js(i)
fs.append(a)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
2015-03-19