python内置函数map和filter都用到了迭代器,获得的返回值均为迭代对象
#使用filter和lambda输出[1,2,3,4,5]中大于4的值
ret = filter(lambda x: x>4,[1,2,3,4,5])
while True:
try:
print(type(ret))
rets = next(ret)
print(rets)
except StopIteration as e:
print('Generrator return value:', e.value)
break
#使用map函数对两个列表中的元素分别求和
ret = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
while True:
try:
print(type(ret))
rets = next(ret)
print(rets)
except StopIteration as e:
print('Generrator return value:', e.value)
break
就如上边的例子
python2中直接返回列表
python3中则返回一个迭代对象,通过next()可以获取结果
map函数:
python2:
python3: