繁体   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