def format_name(s):
return s.lower().capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
return s.lower().capitalize()
print map(format_name, ['adam', 'LISA', 'barT'])
2018-01-21
def cmp_ignore_case(s1, s2):
if(s1[:1].lower() > s2[:1].lower()):
return 1
if(s1[:1].lower() < s2[:1].lower()):
return -1
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
if(s1[:1].lower() > s2[:1].lower()):
return 1
if(s1[:1].lower() < s2[:1].lower()):
return -1
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2018-01-21
指定一些参数值
sorted(iterable, cmp=None, key=None, reverse=False)
sorted_ignore_case = functools.partial(sorted,key=str.lower)
sorted(iterable, cmp=None, key=None, reverse=False)
sorted_ignore_case = functools.partial(sorted,key=str.lower)
2018-01-21
import math
def is_sqr(x):
r = math.sqrt(x)
return r % 1 == 0
print filter(is_sqr, range(1, 101))
这样也可以
def is_sqr(x):
r = math.sqrt(x)
return r % 1 == 0
print filter(is_sqr, range(1, 101))
这样也可以
2018-01-21
def count():
fs = []
for i in range(1, 4):
def f(m=i):
return m*m
fs.append(f)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
既然不能直接用循环变量i,那就将i赋值给m变成非循环变量。
fs = []
for i in range(1, 4):
def f(m=i):
return m*m
fs.append(f)
return fs
f1, f2, f3 = count()
print f1(), f2(), f3()
既然不能直接用循环变量i,那就将i赋值给m变成非循环变量。
2018-01-20
def performance(f):
def s1(x):
start=time.time()
rest=f(x)
end=time.time()
print "call ",f.__name__,"() in",(end-start)
return rest
return s1
@performance
def factorial(n):
return reduce(lambda x,y: x*y,range(1, n+1))
print factorial(10)
def s1(x):
start=time.time()
rest=f(x)
end=time.time()
print "call ",f.__name__,"() in",(end-start)
return rest
return s1
@performance
def factorial(n):
return reduce(lambda x,y: x*y,range(1, n+1))
print factorial(10)
2018-01-20
def calc_prod(lst):
def f(x,y):
return x*y
def lazy():
return reduce(f,lst)
return lazy
f = calc_prod([1, 2, 3, 4])
print f()
def f(x,y):
return x*y
def lazy():
return reduce(f,lst)
return lazy
f = calc_prod([1, 2, 3, 4])
print f()
2018-01-20
class Person(object):
__count = 0
def __init__(self, name):
self.name = name
Person.__count += 1
self.count = Person.__count
p1 = Person('Bob')
p2 = Person('Alice')
print p1.count
print p2.count
try:
print p1.__count
except AttributeError :
print 'AttributeError'
__count = 0
def __init__(self, name):
self.name = name
Person.__count += 1
self.count = Person.__count
p1 = Person('Bob')
p2 = Person('Alice')
print p1.count
print p2.count
try:
print p1.__count
except AttributeError :
print 'AttributeError'
2018-01-20
def cmp_ignore_case(s1,s2):
x = s1.lower()
y = s2.lower()
if ord(x[0])>ord(y[0]):
return 1
if ord(x[0])<ord(y[0]):
return -1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
x = s1.lower()
y = s2.lower()
if ord(x[0])>ord(y[0]):
return 1
if ord(x[0])<ord(y[0]):
return -1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2018-01-20