map()函数
def format_name(s): return s.capitalize() print map(format_name, [‘adam‘, ‘LISA‘, ‘barT‘]) Result: [‘Adam‘, ‘Lisa‘, ‘Bart‘]
把函数作为参数
1 import math 2 3 def add(x, y, f): 4 return f(x) + f(y) 5 6 print add(25, 9, math.sqrt) 7 8 Result: 9 8.0
reduce()函数
def prod(x, y): return x*y print reduce(prod, [2, 4, 5, 7, 12]) Result: 3360
filter()函数
import math def is_sqr(x): return int(math.sqrt(x)) ** 2 == x print([x for x in filter(is_sqr, range(1, 100))]) Result: [1, 4, 9, 16, 25, 36, 49, 64, 81]
print sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=lambda x:x.lower())
时间: 2024-12-15 01:59:52