python-3.x - python 3.5 错误 : can't add `map` results together

标签 python-3.x

我有一段使用 python 2.7 的代码,我正在尝试转换它,以便我可以将它与 python 3.5 一起使用,但由于映射,我在流动代码中遇到错误。解决这个问题的最佳方法是什么?

文件“/Users/newbie/anaconda3/lib/python3.5/site-packages/keras/caffe/caffe_utils.py”,第 74 行,parse_network blobs = top_blobs + bottom_blobs

TypeError: + 不支持的操作数类型: 'ma​​p' 和 'ma​​p'

 def parse_network(layers, phase):
 '''
    Construct a network from the layers by making all blobs and  layers(operations) as nodes.
'''
  nb_layers = len(layers)
  network = {}

   for l in range(nb_layers):
     included = False
     try:
        # try to see if the layer is phase specific
        if layers[l].include[0].phase == phase:
            included = True
     except IndexError:
        included = True

     if included:
        layer_key = 'caffe_layer_' + str(l)  # actual layers, special annotation to mark them
        if layer_key not in network:
            network[layer_key] = []
        top_blobs = map(str, layers[l].top)
        bottom_blobs = map(str, layers[l].bottom)
        blobs = top_blobs + bottom_blobs

        for blob in blobs:
            if blob not in network:
                network[blob] = []
        for blob in bottom_blobs:
            network[blob].append(layer_key)
        for blob in top_blobs:
                network[layer_key].append(blob)
 network = acyclic(network)  # Convert it to be truly acyclic
 network = merge_layer_blob(network)  # eliminate 'blobs', just have layers
 return network

最佳答案

Python 3 中的

map 返回一个迭代器,而 Python 2 中的 map 返回一个列表:

python 2:

>>> type(map(abs, [1, -2, 3, -4]))
<type 'list'>

python 3:

>>> type(map(abs, [1, -2, 3, -4]))
<class 'map'>

(请注意,map 更加特殊,但它肯定不是 list。)

您不能简单地添加迭代器。但是您可以使用 itertools.chain 链接它们:

>>> from itertools import chain
>>> chain(map(abs, [1, -2, 3, -4]), map(abs, [5, -6, 7, -8]))
<itertools.chain object at 0x7fe0dc0775f8>

对于最终结果,您要么必须遍历链,要么对其求值:

>>> for value in chain(map(abs, [1, -2, 3, -4]), map(abs, [5, -6, 7, -8])):
...     print(value)
... 
1
2
3
4
5
6
7
8

>>> list(chain(map(abs, [1, -2, 3, -4]), map(abs, [5, -6, 7, -8])))
[1, 2, 3, 4, 5, 6, 7, 8]

请注意,前者更自然,除非绝对必要,否则应避免将迭代器作为最后一个示例进行评估:它可以节省内存和可能的计算能力(例如,在循环中有中断的地方,以便进一步值不必评估)。

关于python-3.x - python 3.5 错误 : can't add `map` results together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35691489/

相关文章:

dictionary - 如何在Python 3中实现UserDict.DictMixin的功能?

python - 为什么我的整数被转换为 float ?

Python地理空间坐标格式转换

python-3.x - 如何在 Google Colab 笔记本中解压缩非常大的 zip 文件(>6gb)?

python - 根据其他字段重新计算pandas数据框字段的更好方法

python-3.x - 如何找出S3 Bucket上次访问的时间?

python-3.x - 在Seaborn箱图中更改X轴标签

python - python何时复制添加到全局字典的本地列表?

python-3.x - _tkinter.TclError : couldn't connect to display "localhost:10.0" when using wordcloud

python - Canopy 与命令行中运行脚本的区别