map
#对参数迭代器中的每个元素进行操作,返回一个新的迭代器
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
>>> l1=[1,3,5,7,9]
#求列表l1中的每个元素的平方
>>> l2=map(lambda x:x**2,l1)
>>> print(l2)
<map object at 0x7effe739d080>
>>> print(list(l2))
[1, 9, 25, 49, 81]
>>> l3=["python","php","mysql","linux"]
#把列表l3中每个元素变成大写
>>> l4=map(lambda x:x.upper(),l3)
>>> print(l4)
<map object at 0x7effe739d0b8>
>>> print(list(l4))
['PYTHON', 'PHP', 'MYSQL', 'LINUX']
filter
#对迭代器的每个元素进行条件过滤,把符合条件的元素生成一个新的迭代器
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
>>> l3=["python","php","mysql","linux"]
#取得列表l3中以"p"开头的元素
>>> l4=filter(lambda x:x.startswith("p"),l3)
>>> print(list(l4))
['python', 'php']
>>> l1=[99,88,77,66,55,44,33]
#求l1列表中大于55的元素
>>> l2=filter(lambda x:x>55,l1)
>>> print(list(l2))
[99, 88, 77, 66]
reduce
#在python3中,reduce需要导入对应的模块才能使用
from functools import reduce
#调用指定函数对参数列表中的每个元素从左到右进行累加操作
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
>>> l1=[ i for i in range(101)]
>>> print(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
>>> sum1=reduce(lambda x,y:x+y,l1)
>>> print(sum1)
5050
>>> l1=["a","b","c","d"]
>>> sum=reduce(lambda x,y:x+y,l1)
>>> print(sum)
abcd