>>> def f(x):
return x*x
>>> r = map(f,[1,2,3,4,5,6,7,8,9])
>>> list(r) #r是一个Iterator因此通过list()函数让它把整个序列都计算出来并返回一个list
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools import reduce
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
#等同于t = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
#return t[s]
return reduce(fn, map(char2num, s))
或者进一步简化为
from functools import reduce
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s)) #lambda为匿名函数,lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值。lambda语句构建的其实是一个函数对象
def normalize(name):
return name.capitalize()
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
from functools import reduce
def prod(L):
return reduce(lambda x,y: x*y ,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
from functools import reduce
def str2float(s):
sn = s.split('.')[0]+s.split('.')[-1]
#sn = '123456'
def char2num(sn):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[sn]
def str2int(sn):
return reduce(lambda x, y: x * 10 + y, map(char2num, sn))
# sn = 123456
return str2int(sn)/pow(10,len(s)-s.index('.')-1)
# pow(10,len(s)-s.index('.')-1的结果是pow(10,3)=1000,123456/1000=123.456 index是求小数点的位置为3
print('str2float(\'123.456\') =', str2float('123.456'))
过滤元素,与map类似,输入一个函数和一个List
def not_empty(s):
return s and s.strip()
#strip是去除字符串的空格,return语句中的and 相当于 if s then s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
def _odd_iter():
n =1
while True:
n=n+2
yield n
def _not_divisible(n):
return lambda x : x%n>0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)#返回初始序列3开始的奇数序列
yield n
it = filter(_not_divisible(n),it) # 构造新序列
for n in primes():
if n < 1000:
print(n)
else:
break
def is_palindrome(n):
n=str(n)
return n[:] ==n[::-1]
output = filter(is_palindrome, range(1, 1000))
print(list(output))
key函数,反向排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
tuple按照名字和成绩排序
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
L2 = sorted(L, key=by_name)
print(L2)
def by_score(t):
return -t[1]
L3 =sorted(L,key=by_score)
print(L3)