回溯typeerror python

2024-10-02 20:31:52 发布

您现在位置:Python中文网/ 问答频道 /正文

从文件中的一个列表中,我试图得到两个被划分的新列表:子集合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]

我在这里做错什么了?你知道吗


Tags: oftheconfigmapinputindexobjectis
2条回答

如错误消息所示,不能为map对象下标(方括号)。在python中,映射是一种iterable类型,这意味着从映射中获取数据的唯一方法是一次遍历一个元素。如果要为其下标,则需要将其存储为列表。你知道吗

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

正如这个简单的示例所示,不能为map对象下标。你知道吗

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

要从map对象中获取数据:

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


0
1
23
4
5
6
6

您需要将地图对象转换为列表。你知道吗

list(yourmapobject)

相关问题 更多 >