python - Python TypeError:只能将列表(不是“映射”)连接到列表
问题描述
我的程序中有两行看起来相当简单,但让我有些头疼
这里是
costs = sum([map(int, f.readline().strip().split(' ')) for i in range(8)], [])
awards = sum([map(int, f.readline().strip().split(' ')) for i in range(8)], [])
它给了我错误:TypeError: can only concatenate list (not "map") to list
在我看来,这与 python 2 到 python 3 版本有关,但我无法弄清楚!
我被困了几个小时,找不到解决方案。有什么帮助吗?
解决方案
您可以使用链,而不是以这种方式对列表求和:
list(chain.from_iterable(
map(int, f.readline().strip().split(' ')) for i in range(8)))
这将更加节省内存,并且对于较大的循环值,它也可能变得更快。
使用sum
会导致创建许多临时列表......如果我们在sum(L, [])
内部使用 then 这将产生许多中间列表(列表)
sum(L, []) ->
tmp = [] + L[0]
tmp = tmp + L[1]
...
tmp = tmp + L[7]
这个总和的每一步,都会tmp
在构建一个新的时丢弃前一个。
推荐阅读
- ruby-on-rails - 带有 has_many through 和 join 表的简单表格
- hashmap - 访问对列表数组中的值
- reactjs - 如何在 reactjs 应用程序中进行复选框切换?不使用我的代码
- oracle - oci_bind_by_name(): ORA-01036
- facebook-graph-api - 如何解决 Facebook 图形 API 中“(#100)尝试访问节点类型(帖子)上不存在的字段(喜欢)”的错误
- java - 无法从 docker Linux 上的 javaKerberos Sql Server 连接中找到默认领域
- php - 获取多维数组中具有值的数组键
- android - com.sec.android.provider.badge.permission.READ 在需要时在 Android 中
- java - 形状构造的设计模式
- apache-spark - 在 Apache Spark/Databricks 中分离坏数据行