filter() map() 和 zip() 返回迭代器而不是序列
Python 2.x <= 2.7
在 Python 2 filter
中 , map
和 zip
内置函数返回一个序列。map
和 zip
总是返回一个列表,而 filter
的返回类型取决于给定参数的类型:
>>> s = filter(lambda x: x.isalpha(), 'a1b2c3')
>>> s
'abc'
>>> s = map(lambda x: x * x, [0, 1, 2])
>>> s
[0, 1, 4]
>>> s = zip([0, 1, 2], [3, 4, 5])
>>> s
[(0, 3), (1, 4), (2, 5)]
Python 3.x >= 3.0
在 Python 3 filter
中 , map
和 zip
返回迭代器:
>>> it = filter(lambda x: x.isalpha(), 'a1b2c3')
>>> it
<filter object at 0x00000098A55C2518>
>>> ''.join(it)
'abc'
>>> it = map(lambda x: x * x, [0, 1, 2])
>>> it
<map object at 0x000000E0763C2D30>
>>> list(it)
[0, 1, 4]
>>> it = zip([0, 1, 2], [3, 4, 5])
>>> it
<zip object at 0x000000E0763C52C8>
>>> list(it)
[(0, 3), (1, 4), (2, 5)]
由于 Python 2 itertools.izip
相当于 Python 3,所以在 Python 3 中删除了 zip
izip
。