关于map的一些深入问题(Python)

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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值