簡體   English   中英

回溯TypeError Python

[英]Backtracking typeerror python

從文件的列表中,我嘗試獲得2個划分的新列表:子集A和子集B。這意味着子集A中的元素(整數)應等於子集B。(此程序使用回溯來解決問題的方式。)但是我越來越:

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]

我在這里做錯了什么?

如錯誤消息所提示,您不能在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

並從地圖對象中獲取數據:

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


0
1
23
4
5
6
6

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

list(yourmapobject)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM