sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # 利用cmp函数
sorted(L, key=lambda x:x[1]) # 利用key
sorted(L, key=lambda x:x[1]) # 利用key
2018-02-01
def calc(x,y):
return x*y
def calc_prod(lst):
def delay_calc():
return reduce(calc, lst)
return delay_calc
f = calc_prod([1, 2, 3, 4])
print f()
这一章我觉得学过C语言的人应该很好理解, f相当于是 接收一个函数返回了函数指针, 再通过f()来调用(C语言中用*f来调用)
return x*y
def calc_prod(lst):
def delay_calc():
return reduce(calc, lst)
return delay_calc
f = calc_prod([1, 2, 3, 4])
print f()
这一章我觉得学过C语言的人应该很好理解, f相当于是 接收一个函数返回了函数指针, 再通过f()来调用(C语言中用*f来调用)
2018-02-01
def cmp_ignore_case(s1, s2):
if s1.title() > s2.title():
return 1
elif s1.title() < s2.title():
return -1
else:
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
srot的内部实现我不清楚, 但肯定是调用了某种排序算法, 这里的比较, 如果返回-1, 则s1排在前面, 返回1, 则s1排在后面
if s1.title() > s2.title():
return 1
elif s1.title() < s2.title():
return -1
else:
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
srot的内部实现我不清楚, 但肯定是调用了某种排序算法, 这里的比较, 如果返回-1, 则s1排在前面, 返回1, 则s1排在后面
2018-02-01
class Person(object):
def __init__(self, name, score):
setattr(self,'name',name)
self.__score = score
p = Person('Bob', 59)
print p.name
try:
print p.__score
except:
print ('AttributeError')
def __init__(self, name, score):
setattr(self,'name',name)
self.__score = score
p = Person('Bob', 59)
print p.name
try:
print p.__score
except:
print ('AttributeError')
2018-02-01
class Person(object):
def __init__(self,name,gender,birth,**kw):
setattr(self,'name',name)
setattr(self,'gender',gender)
setattr(self,'birth',birth)
for k,v in kw.iteritems():
setattr(self, k,v)
def __init__(self,name,gender,birth,**kw):
setattr(self,'name',name)
setattr(self,'gender',gender)
setattr(self,'birth',birth)
for k,v in kw.iteritems():
setattr(self, k,v)
2018-02-01
def format_name(s):
return s[:1].upper()+s[1:].lower()
print map(format_name, ['adam', 'LISA', 'barT'])
return s[:1].upper()+s[1:].lower()
print map(format_name, ['adam', 'LISA', 'barT'])
2018-01-31
#借助Fraction()函数,可避免递归 求最大公约数
def __str__(self):
if self.p % self.q != 0:
s = '%s/%s' % ( self.p, self.q )
temp = Fraction(s)
return str(temp)
else:
temp = Fraction( '%s/%s' % ( self.p, self.q ) )
return '%s/%s' % (temp,1)
def __str__(self):
if self.p % self.q != 0:
s = '%s/%s' % ( self.p, self.q )
temp = Fraction(s)
return str(temp)
else:
temp = Fraction( '%s/%s' % ( self.p, self.q ) )
return '%s/%s' % (temp,1)
2018-01-31
@property
def grade(self):
if self.__score>=80:
return "A"
elif self.__score<60:
return 'C'
else:
return 'B'
def grade(self):
if self.__score>=80:
return "A"
elif self.__score<60:
return 'C'
else:
return 'B'
2018-01-31