map用法:
>>> a = map(int, '12') # 对可迭代对象的每个元素进行int函数映射,生成迭代器
>>> list(a)
[1, 2]
>>> a = map(lambda x, y:x+y, *([1, 2], [3, 4])) # 等价于 map(f, iter1, iter2),一一对应传参
>>> list(a)
[4, 6]
>>> a = map(lambda x, y:x+y, *([1, 2], [3, 4, 5])) # 等价于 map(f, iter1, iter2) ,最小长度结束
>>> list(a)
[4, 6]
易错问题:
>>> a = map(None, [1, 2], [3, 4, 5]) # 结果应该为: 迭代器 map object((1, 3), (2, 4), (None, 5))
>>> list(a) # 报错了
Traceback (most recent call last):
File "<pyshell#02>", line 1, in <module>
list(a)
TypeError: 'NoneType' object is not callable
>>> for i in a:
# 按道理,迭代器通过for循环,可以得到输出i
print(i)
Traceback (most recent call last):
File "<pyshell#02>", line 1, in <module>
for i in a:
TypeError: 'NoneType' object is not callable
解决问题:
>>> from itertools import zip_longest
>>> s = []
>>> a = [1, 2]
>>> b = [3, 4, 5]
>>> for i, j in zip_longest(a, b):
s.append((i, j))
>>> s
[(1, 3), (2, 4), (None, 5)]
涉及到zip:
>>> a = [1, 2]
>>> b = [3, 4, 5]
>>> c = zip(a, b) # 迭代器 zip object((1, 3), (2, 4)),最小长度结束
>>> list(c)
[(1, 3), (2, 4)]
参考:
https://stackoverflow.com/questions/35002646/calling-none-in-maps-in-python-3