简体   繁体   English

回溯TypeError Python

[英]Backtracking typeerror python

Out of a list in the file, i am trying to get 2 divided new lists: Subset A, and Subset B. By that means the elements (integers) in Subset A should be equal to Subset B. (This program uses backtracking to solve the problem by the way.) However i am getting: 从文件的列表中,我尝试获得2个划分的新列表:子集A和子集B。这意味着子集A中的元素(整数)应等于子集B。(此程序使用回溯来解决问题的方式。)但是我越来越:

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

and an error: 和一个错误:

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

The constructor function that i indicated the map in is: 我在其中指示地图的构造函数是:

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

and the function where i am getting an error: 以及我遇到错误的功能:

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]

What am i doing wrong in here? 我在这里做错了什么?

As the error message suggests, you cannot subscript (square bracket) a map object. 如错误消息所提示,您不能在map对象下标(方括号)。 Maps are a type of iterable in python, meaning the only way to get data out of them is to iterate through them one element at a time. 地图是python中的一种可迭代的类型,这意味着从中获取数据的唯一方法是一次遍历一个元素。 If you want to subscript it, you need to store it as a list. 如果要下标,则需要将其存储为列表。

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

As this simple example shows, you cannot subscript a map object. 如这个简单的示例所示,您不能对地图对象下标。

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

And to get data out of the map object: 并从地图对象中获取数据:

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