2014-05-10 38 views
1

在文件列表中,我試圖得到2個分開的新列表:子集A和子集B.這意味着子集A中的元素(整數)應該等於子集B.該程序使用回溯的方式來解決問題),但是我收到:Backtracking typeerror python

Subset A: <map object at 0x311b110> 
Subset B: <map object at 0x311b190> 

和一個錯誤:

 line 93, in getSuccessors 
    cfgA.subA.append(config.input[config.index]) 
TypeError: 'map' object is not subscriptable 

,我指定的地圖中的構造函數是:

def mkPartitionConfig(filename): 
    """ 
    Create a PartitionConfig object. Input is: 
     filename # name of the file containing the input data 

    Returns: A config (PartitionConfig) 
    """ 


    pLst = open(filename).readline().split() 
    print(pLst) 
    config = PartitionConfig 
    config.input = map(int, pLst) 
    config.index = 0 
    config.subA = [] 
    config.subB = [] 
    return config 

,並在那裏我得到一個錯誤的功能:

def getSuccessors(config): 
    """ 
    Get the successors of config. Input is: 
     config: The config (PartitionConfig) 
    Returns: A list of successor configs (list of PartitionConfig) 
    """ 

    cfgA = deepcopy(config) 
    cfgB = deepcopy(config) 
    cfgA.subA.append(config.input[config.index]) 
    cfgB.subB.append(config.input[config.index]) 
    cfgA += 1 
    cfgB += 1 

    return [configA, configB] 

什麼我這裏做錯了嗎?

+1

? –

回答

2

由於錯誤消息提示,您不能下標(方括號)a map對象。在Python中,地圖是可迭代的的一種類型,這意味着從中獲取數據的唯一方法是一次遍歷它們中的一個元素。如果你想要下標,你需要把它作爲一個列表存儲。

config.input = list(map(int, pLst)) 

正如這個簡單的例子所示,你不能下標地圖對象。

>>> x = [0, 1, 23, 4, 5, 6, 6] 
>>> y = map(str, x) 
>>> y 
<map object at 0x02A69DB0> 
>>> y[1] 
Traceback (most recent call last): 
    File "<pyshell#4>", line 1, in <module> 
    y[1] 
TypeError: 'map' object is not subscriptable 

而得到的數據進行地圖對象的:你爲什麼要使用地圖(INT,PLST)

>>> for i in y: 
    print(i) 


0 
1 
23 
4 
5 
6 
6 
+0

現在感謝了 – user3408174

0

您需要將地圖對象轉換爲列表。

list(yourmapobject)