【问题标题】:TypeError: '_SpecialGenericAlias' object does not support item assignmentTypeError:“_SpecialGenericAlias”对象不支持项目分配
【发布时间】:2021-08-05 20:27:14
【问题描述】:

我正在使用 Python 编写人工智能中的约束满足问题:

from typing import Generic, TypeVar, Dict, List, Optional
from abc import ABC, abstractmethod
V = TypeVar('V')
D = TypeVar('D')

class Constraint(Generic[V,D], ABC):
    def __init__(self, variables: List[V]) -> None:
        self.variables = variables

    @abstractmethod
    def satisfied(self, assignment: Dict[V, D]) -> bool:
        ...


class CSP(Generic[V, D]):
    def __init__(self, variables: List[V], domains: Dict[V, List[D]]) -> None:
        self.variables: List[V] = variables
        self.domain: Dict[V, List[D]] = domains
        self.constraints: Dict[V, List[Constraint[V, D]]] = {}
        for variable in self.variables:
            self.constraints[variable] = []

    def add_constraint(self, constraint: Constraint[V, D]) -> None:
        for variable in constraint.variables:
            if variable not in constraint.variables:
                print("Variable in Constraint, not in CSP")
            else:
                self.constraints[variable].append(constraint)

    def consistent(self, variable: V, assignment: Dict[V, D]) -> bool:
        for constraint in self.constraints[variable]:
            if not constraint.satisfied(assignment):
                return False
        return True

    def backtracking_search(self, assignment: Dict[V, D] = {}) -> Optional[Dict[V, D]]:
        if len(assignment) == len(self.variables):
            return assignment
        unassigned: List[V] = [v for v in self.variables if v not in assignment]
        first: V = unassigned[0]
        for value in self.domains[first]:
            local_assignment = assignment.copy()
            local_assignment[first] = value
            if self.consistent(first, local_assignment):
                result: Optional[Dict[V, D]] = self.backtracking_search(local_assignment)
                if result is not None:
                    return result
        return None


class MapColoringConstraint(Constraint[str, str]):
    def __init__(self, place1: str, place2: str) -> None:
        super().__init__([place1, place2])
        self.place1: str = place1
        self.place2: str = place2

    def satisfied(self, assignment: Dict[V, D]) -> bool:
        if self.place1 not in assignment or self.place2 not in assignment:
            return True
        return assignment[self.place1] != assignment[self.place2]


variables: List[str] = ["DJ", "SO", "ET", "KE", "UG", "TA", "RW", "BU"]
domains = Dict[str, List[str]] = {}
for variable in variables:
    domains[variable].append("Red")
    domains[variable].append("Green")
    domains[variable].append("Blue")
csp: CSP[str, str] = CSP(variables, domains)
edges = [("DJ", "SO"), ("DJ", "ET"),
         ("SO", "KE"), ("SO", "ET"),
         ("ET", "KE"), ("KE", "UG"),
         ("KE", "TA"), ("UG", "TA"),
         ("UG", "RW"), ("TA", "BU"),
         ("TA", "RW"), ("RW", "BU")]
for i, j in edges:
    print(i, j)

错误发生为:

第 64 行,在 域 = 字典 [str, 列表 [str]] = {} TypeError: '_SpecialGenericAlias' 对象不支持项目分配

我不完全知道正在发生的问题,我必须声明字典“域”,因为这是问题所必需的,有人可以帮我吗?

【问题讨论】:

    标签: python list dictionary typing


    【解决方案1】:

    问题是将 DataType 分配给 变量

    domains = Dict[str, List[str]] = {}
    

    无法为变量“域”分配 DataType 和类型字典的分配。这就是发生错误的原因。但是,我使用以下方法修复了它:

    domains: Dict[str, List[str]] = {}
    

    现在,它工作正常。 很抱歉给您带来不便,我真的希望有一天它会对某人有所帮助。

    【讨论】:

    • 但是它在我的机器上给出了一个 KeyError
    • 是的,这是个问题。这是您可以解决的方法。而不是使用:domains[variable].append("Red") domain[variable].append("Green") domain[variable].append("Blue") 使用:domains[variable] = ["Red", " Green", "Blue"] 这对我有用。
    猜你喜欢
    • 2016-07-31
    • 2014-02-18
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多