Pythonfilter(),map()和zip()返回迭代器,而不是序列
示例
在Python2filter,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)]
在Python3filter,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)]