python内建了map()和reduce()函数
map():
map()
函数接收两个参数,一个是函数,一个是Iterable
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator
返回
def f(x):
return x*x
r=map(f,[1,2,3,4,5])
print(list(r)) #[1, 4, 9, 16, 25]
print(list(map(str,[1,2,3,4,5,6,7,8,9]))) #['1', '2', '3', '4', '5', '6', '7', '8', '9']
reduce():
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算
from functools import reduce
def add(x,y):
return x+y
print(reduce(add,[1,2,3,4,5,6])) #21=1+2=3=4+5+6
filter():
filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素
def is_odd(n):
return n%2==1
print(list(filter(is_odd,[1,2,3,4,5,6,9,10,15]))) #[1, 3, 5, 9, 15]
def not_empty(s):
return s and s.strip() #Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
print(list(filter(not_empty,['A','','B',None,'C','']))) #['A', 'B', 'C']
sorted()
Python内置的sorted()
函数就可以对list进行排序:
print(sorted([36,5,-12,9,-21],key=abs)) #[5, 9, -12, -21, 36]按绝对值大小排
print(sorted(['bob', 'about', 'Zoo', 'Credit'])) #['Credit', 'Zoo', 'about', 'bob']
#默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面