You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python运行报错:找不到abstractcollection模块及相关类获取咨询

解决"no module named 'abstractcollection'"错误及相关文件获取问题

错误原因

abstractcollection和graph不是PyPI上的公开模块,这类模块大多是高校数据结构课程的自定义配套代码,所以用pip search或pip install找不到。

获取并使用目标文件的方法

直接创建对应的.py文件,将核心实现代码写入即可:

1. 创建abstractcollection.py(包含AbstractCollection类)

from abc import ABC, abstractmethod

class AbstractCollection(ABC):
    def __init__(self, source_collection=None):
        self._size = 0
        if source_collection:
            for item in source_collection:
                self.add(item)

    @abstractmethod
    def add(self, item):
        pass

    def is_empty(self):
        return len(self) == 0

    def __len__(self):
        return self._size

    def __str__(self):
        return "{" + ", ".join(map(str, self)) + "}"

    def __add__(self, other):
        result = type(self)(self)
        for item in other:
            result.add(item)
        return result

    def __eq__(self, other):
        if self is other:
            return True
        if type(self) != type(other) or len(self) != len(other):
            return False
        other_iter = iter(other)
        for item in self:
            if item != next(other_iter):
                return False
        return True

2. 创建graph.py(包含LinkedDirectedGraph类)

from abstractcollection import AbstractCollection

class LinkedDirectedGraph(AbstractCollection):
    def __init__(self, source_collection=None):
        super().__init__(source_collection)
        self._vertices = dict()  # 存储顶点与邻接表映射
        self._edges = dict()     # 存储边(起点,终点)与权重映射

    def add_vertex(self, vertex):
        if vertex not in self._vertices:
            self._vertices[vertex] = list()
            self._size += 1

    def add_edge(self, from_vertex, to_vertex, weight=1):
        if from_vertex not in self._vertices:
            self.add_vertex(from_vertex)
        if to_vertex not in self._vertices:
            self.add_vertex(to_vertex)
        edge_key = (from_vertex, to_vertex)
        if edge_key not in self._edges:
            self._vertices[from_vertex].append(to_vertex)
            self._edges[edge_key] = weight

    def get_vertices(self):
        return list(self._vertices.keys())

    def get_edges(self):
        return list(self._edges.items())

    def __iter__(self):
        return iter(self._vertices.keys())

使用注意事项

  • 将上述两个文件放在你的Python项目根目录下(和你运行的主代码文件同一文件夹),即可直接通过import abstractcollection或from graph import LinkedDirectedGraph导入使用。
  • 如果你的代码对这两个类有额外方法要求,可以根据需求补充对应的实现逻辑。

内容的提问来源于stack exchange,提问作者John Murphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:30:56