繁体   English   中英

“TypeError: unhashable type: 'list'” 使用.add 将数组添加到列表时。 有什么解决办法吗? (Python)

[英]"TypeError: unhashable type: 'list'" when using .add to add array to list. Any work around ? (Python)

我正在尝试实现广度优先搜索,并在visited.add(state) 命令上收到“TypeError:unhashable type:'list'”。 initState 输入是一个数字数组 ([2,2,0,0,1]),future_State() 的返回值是相同格式的 arrays 列表。 关于如何解决这个问题的任何想法?

一些研究指出了hash () 方法,但我无法让它工作:/

      def BFS(initState):
            initState = currentState
            if isGoal(initState) :
                return initState

            visited = set()
            queue = [initState]

            while queue:
                state = queue.pop()
                if isGoal(state) == True:
                    return state

                visited.add(state)

                for child in future_State(state):
                    if child in visited:
                        continue
                    if child not in queue:
                        queue.append(child)

Python 中的集合通过 hash 表实现。 您收到的错误消息意味着您无法将列表添加到集合中,因为无法为该类型的变量(列表)计算 hash 键。 如果要将state的值添加到访问数组中,可以执行联合:

visited = visited.union(state)

否则,如果您希望集合的每个元素都是一个列表,您应该使用一个列表不是一个集合,并实施一个解决方案来避免重复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM