1. filter
函数原型:
filter(function, iterable)
过滤器,过滤掉不满足函数 function
的元素,重新返回一个新的迭代器。
其中 function
函数的第一个参数是可迭代对象 iterable
中的一个元素,也就是说函数 function
依次接收 iterable
可迭代对象的每一个元素,并判断每一个元素是否符合 function
的条件。
In [29]: a = [1,2,3,4,5]
In [30]: def fun(a):
...: ret = []
...: if a > 3:
...: ret.append(a)
...: return ret
...:
In [31]: for i in filter(fun, a):
...: print(i)
...:
4
5
In [32]: list(filter(fun, a))
Out[32]: [4, 5]
2. map
函数原型
map(function, iterable, ...)
它将 function
映射于 iterable
中的每一项,并返回一个新的迭代器。其中这个函数 function
一定要有返回值。
In [33]: a = [1,2,3,4,5]
In [34]: map(lambda x: x*2, a)
Out[34]: <map at 0x843d400>
In [35]: ret = map(lambda x: x*2, a)
In [37]: list(ret)
Out[37]: [2, 4, 6, 8, 10]
同时我们, map
函数支持传入多个可迭代对象。当传入多个可迭代对象时,输出元素个数等于较短序列长度。
如下,传入两个列表, function
就需要接受两个参数,取值分别对应第一、第二个列表中的元素。找到同时满足第一个列表的元素为奇数,第二个列表对应位置的元素为偶数的元素。
In [38]: xy = map(lambda x,y: x%2==1 and y%2==0, [1,3,2,4,1],[3,2,1,2])
In [39]: for i in xy:
...: print(i)
...:
False
True
False
False
In [40]: a = [1,2,3,4,5]
In [41]: b = [10,11]
In [42]: ret = map(lambda i,j: i+j, a, b)
In [43]: list(ret)
Out[43]: [11, 13]
3. reduce
函数原型:
reduce(function, iterable[, initializer])
reduce
函数在 Python 3
中位于 functools
模块中,使用前需要先导入。
In [72]: from functools import reduce
reduce
函数中第一个参数是函数 function
。 function
函数,参数个数必须为 2,是可迭代对象 iterable
内的连续两项。它的计算过程是依次将 iterable
2 个元素为单位传递给 function
。
In [45]: from functools import reduce
In [46]: reduce(lambda x,y: x+y,list(range(5)))
Out[46]: 10
即它的计算结果是 0+1+2+3+4=10
4. reversed
函数原型:
reversed(seq)
重新生成一个反向迭代器,对输入的序列实现反转。注意:它会返回一个新的迭代序列。
In [47]: a = [1,2,3,4,5]
In [48]: ret = reversed(a)
In [49]: ret
Out[49]: <list_reverseiterator at 0x8940f60>
In [50]: list(ret)
Out[50]: [5, 4, 3, 2, 1]
5. sorted
函数原型:
sorted(iterable, *, key=None, reverse=False)
实现对可迭代对象的排序, key
参数和 reverse
参数必须为关键字参数,都可省略。
In [51]: a = [3,1,2,5,4]
In [52]: ret = sorted(a, reverse=True)
In [53]: ret
Out[53]: [5, 4, 3, 2, 1]
In [54]: ret = sorted(a, reverse=False)
In [55]: ret
Out[55]: [1, 2, 3, 4, 5]
可迭代对象的元素也是一个复合对象,如为字典。依据依据为字典键的值, sorted
的 key
函数就会被用到。
In [62]: d = [{'a':111, 'b':222, 'c':333}, {'a':11, 'b':22, 'c':33}, {'a':1, 'b':2, 'c':3}]
In [63]: sorted(d,key=lambda x:x['a'])
Out[63]:
[{'a': 1, 'b': 2, 'c': 3},
{'a': 11, 'b': 22, 'c': 33},
{'a': 111, 'b': 222, 'c': 333}]
6. iter
函数原型:
iter(object[, sentinel])
返回一个严格意义上的可迭代对象,其中,参数 sentinel 可有可无。
In [64]: a = [1,2,3]
In [65]: ret = iter(a)
In [66]: ret
Out[66]: <list_iterator at 0x7feba20>
In [67]: ret.__next__()
Out[67]: 1
In [68]: ret.__next__()
Out[68]: 2
In [69]: ret.__next__()
Out[69]: 3
In [70]: ret.__next__()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-70-6685d4123b21> in <module>
----> 1 ret.__next__()
StopIteration:
In [71]: for i in ret:
...: print(i)
...:
In [72]:
可以看到最后 for i in ret
中已经没有元素可进行迭代,所以 print(i)
不会有值再打印。
只要 iterable
对象支持可迭代协议,即自定义了 __iter__
函数,便都能配合 for
依次迭代输出其元素。
In [73]: class Iter(object):
...: def __init__(self):
...: self._list = [1,2,3]
...: def __iter__(self):
...: print("enter __iter__")
...: return iter(self._list)
...:
In [74]: m = Iter()
In [77]: for i in m:
...: print(i)
...:
enter __iter__
1
2
3
In [78]:
如果在 Iter
类中不使用 iter(self._list)
则会有如下错误:
In [78]: class Iter(object):
...: def __init__(self):
...: self._list = [1,2,3]
...: def __iter__(self):
...: print("enter __iter__")
...: return self._list
...:
In [79]: m = Iter()
In [80]: for i in m:
...: print(i)
...:
enter __iter__
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-80-9cd7b7f0b3b5> in <module>
----> 1 for i in m:
2 print(i)
3
TypeError: iter() returned non-iterator of type 'list'
7. zip
zip()
函数接受任意多个(包括 0
个和 1
个)序列作为参数,返回一个 tuple
列表。
In [21]: x = [1,2,3]
In [22]: y = [4,5,6]
In [23]: z = [7,8,9]
In [24]: zip(x,y,z)
Out[24]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
In [25]: a = ['a','b','c']
In [26]: b = [1,2,3]
In [27]: zip(a,b)
Out[27]: [('a', 1), ('b', 2), ('c', 3)]
In [28]: dict(zip(a,b))
Out[28]: {'a': 1, 'b': 2, 'c': 3}
这个函数可以方便的将两个序列结合起来,然后再调用 for
循环语句,在实际项目中有很大的用处。