zip、map和filter函数生成的可迭代对象均有自己的迭代器,可使用next函数执行迭代操作
1.zip函数
zip函数参数为多个可迭代对象,每次从每个可迭代对象中取一个值组成一个元组,直到可迭代对象中的值取完,生成的zip对象包含了一系列元组。
>>> x=zip((1,2,3),(4,5,6))
>>> x
<zip object at 0x00000000021D2048>
>>> next(x)
(1, 4)
>>> next(x)
(2, 5)
>>> next(x)
(3, 6)
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> x=zip((1,2),'ab',[5,6])
>>> next(x)
(1, 'a', 5)
>>> next(x)
(2, 'b', 6)
2、map函数
map函数用于将函数映射到可迭代对象,对可迭代对象中的每个元素应用该函数,函数返回值包含在生成的map对象中。
>>> x=map(ord,'abc')
>>> x
<map object at 0x00000000021CF908>
>>> next(x)
97
>>> next(x)
98
>>> next(x)
99
>>> list(map(ord,'abc')) #用map对象生成列表
[97, 98, 99]
3.filter函数
filter函数用指定的函数处理可迭代对象。若函数返回值为真,则对应可迭代对象元素包含在生成的filter对象序列中。
>>> x=filter(bool,(1,-1,0,'ab','',(),[],{},(1,2),[1,2],{1,2},{'a':1}))
>>> x
<filter object at 0x00000000021CF940>
>>> next(x)
1
>>> list(x) # 将迭代器转换为列表,不包含已迭代的值
[-1, 'ab', (1, 2), [1, 2], {1, 2}, {'a': 1}]