首页 > 解决方案 > 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 版本有关,但我无法弄清楚!

我被困了几个小时,找不到解决方案。有什么帮助吗?

标签: python

解决方案


您可以使用链,而不是以这种方式对列表求和:

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在构建一个新的时丢弃前一个。


推荐阅读