2016-02-29 37 views
3

我有一段代碼使用python 2.7,我試圖轉換它,以便我可以在python 3.5中使用它,但是我在流動代碼中遇到錯誤由於地圖。解決這個問題的最好方法是什麼?python 3.5中的錯誤:無法將`map`結果加在一起

文件 「/Users/newbie/anaconda3/lib/python3.5/site-packages/keras/caffe/caffe_utils.py」,線74,在parse_network 斑點= top_blobs + bottom_blobs

類型錯誤:爲+不受支持的操作數類型: '地圖' 和 '地圖'

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 
+0

您可能還想考慮將這段代碼放到[代碼評論](http://codereview.stackexchange.com/)(一旦修復),因爲這三個for-loops在彼此之上可以被簡化爲許多。例如,一個'network = collections.defaultdict(list)'可以擺脫blob循環中完整的blob。 – Evert

回答

4

在Python 3返回一個迭代map,而map在Python 2返回一個列表:

的Python 2:

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

的Python 3:(注意,map是比較特殊的甚至有點,但它肯定不是一個list

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

你不能簡單地添加迭代器。但是你可以把它們連,使用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] 

注前者更自然,除非絕對必要,否則評估迭代器應作爲最後一個示例應避免:它可以節省內存和可能的計算能力(例如,存在循環中斷,以便進一步的值不必評估)。