小编hop*_*ley的帖子

在 Python 中创建唯一对象数组

假设我有一个程序可以创建一些带有线和点的方案。所有直线均由两点确定。有这些类:

class Coordinates(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y


class Point(object):
    def __init__(self, coordinates):
        self.coordinates = coordinates

class Line(object):
    def __init__(self, coordinates_1, coordinates_2):
        self.coordinates_1 = coordinates_1
        self.coordinates_2 = coordinates_2
Run Code Online (Sandbox Code Playgroud)

方案采用线列表并创建唯一点列表。

class Circuit(object):
    def __init__(self, element_list):
        self.line_list = element_list
        self.point_collection = set()
        self.point_collection = self.generate_points()

    def generate_points(self):
        for line in self.line_list:
            coordinates_pair = [line.coordinates_1, line.coordinates_2]
            for coordinates in coordinates_pair:
                self.point_collection.add(Point(coordinates))
        return self.point_collection
Run Code Online (Sandbox Code Playgroud)

哪些变体能够创建唯一对象的列表或集合?如何不使用集合和排序,仅使用循环和条件来做到这一点?以及如何更简单地做到这一点?

UPD。我附加的代码无法正常工作。我尝试在 Point 类中添加hash和eq方法:

class Point(object):
def __init__(self, coordinates):
    self.coordinates = coordinates …
Run Code Online (Sandbox Code Playgroud)

python arrays algorithm collections list

2
推荐指数
1
解决办法
4090
查看次数

标签 统计

algorithm ×1

arrays ×1

collections ×1

list ×1

python ×1