博客
关于我
map 没有len函数
阅读量:342 次
发布时间:2019-03-03

本文共 569 字,大约阅读时间需要 1 分钟。

在Python 3中,map对象已经不再支持len()方法,这可能会导致一些常见错误。许多开发者在处理迭代操作时可能会遇到这个问题。以下是一些解决方案。

错误示例:

x = [[1, 'a'], [2, 'b'], [3, 'c']]len(map(lambda a: a[0], x))

错误原因:在Python 3中,map返回的对象是map对象,而不是列表或元组。map对象不具备len()方法,因此直接调用len()会导致TypeError。

解决方案一:强制转换为列表或元组将map对象转换为列表后再调用len()方法:

len(list(map(lambda a: a[0], x)))

解决方案二:使用列表推导式替代map这种方法避免了使用map,并且代码更加直观:

my_list = [a[0] for a in x]len(my_list)

注意事项:

  • 在选择解决方案时,请根据具体需求选择最合适的方式。如果需要保持代码的简洁,可以优先考虑使用列表推导式。
  • 尽量避免在已有可读性较好的代码中进行改动,除非必要。
  • 如果需要保持与其他代码风格一致,可以考虑在函数内部使用map,并确保其输出类型符合需求。

通过上述方法,可以有效避免在Python 3中使用map对象时的len()方法错误,同时保持代码的可读性和可维护性。

转载地址:http://cabq.baihongyu.com/

你可能感兴趣的文章
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>