最赞回答 / 流年丶岁月
很简单的。你直接 L2 = sorted(['Bart', 'Adam', 'Lisa']) 就是你说的意思。但是这里的L1不是字符串的list,里面都是Person的实例。对这些实例肯定就没有办法按照默认排序方式了,要自己添一个排序方式告诉它,也就是 L2 = sorted(L1, lambda x,y: cmp(x.name,y.name))
2018-03-05
import math
def c(s1):
return s1.lower()
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=c,reverse=True))
def c(s1):
return s1.lower()
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=c,reverse=True))
2018-03-05
def prod(x, y):
return x*y
print reduce(prod, [2, 4, 5, 7, 12])
return x*y
print reduce(prod, [2, 4, 5, 7, 12])
2018-03-04
class Fib(object):
def __call__(self, num):
lst = [0, 1]
if num < 1:
return
i = 0
while i < num:
lst.append(lst[i] + lst[i + 1])
i += 1
return lst[:num]
def __call__(self, num):
lst = [0, 1]
if num < 1:
return
i = 0
while i < num:
lst.append(lst[i] + lst[i + 1])
i += 1
return lst[:num]
2018-03-04
def cmp_ignore_case(s1, s2):
return cmp(s1.lower(),s2.lower())
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
return cmp(s1.lower(),s2.lower())
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2018-03-04
def cmp_ignore_case(s1, s2):
S1 = s1.lower()
S2 = s2.lower()
if S1 > S2:
return 1
if S1 < S2:
return -1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
S1 = s1.lower()
S2 = s2.lower()
if S1 > S2:
return 1
if S1 < S2:
return -1
return 0
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2018-03-04
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1,101))
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1,101))
2018-03-04
def format_name(s):
return s.title()
print map(format_name, ['adam', 'LISA', 'barT'])
return s.title()
print map(format_name, ['adam', 'LISA', 'barT'])
2018-03-04
import math
def add(x, y, f):
return f(x) + f(y)
print add(25, 9, math.sqrt)
def add(x, y, f):
return f(x) + f(y)
print add(25, 9, math.sqrt)
2018-03-04
import functools
# sorted_ignore_case = functools.partial(sorted,key=lambda str : str.lower())
sorted_ignore_case = functools.partial(sorted,cmp=lambda str1, str2 : 1 if str1.lower() > str2.lower() else -1)
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
# sorted_ignore_case = functools.partial(sorted,key=lambda str : str.lower())
sorted_ignore_case = functools.partial(sorted,cmp=lambda str1, str2 : 1 if str1.lower() > str2.lower() else -1)
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
2018-03-04