繁体   English   中英

如何检查一个列表是否等于使用类创建的另一个列表?

[英]How to check if one list is equal to another list created using a class?

from math import pi

class Circle(object):
    'Circle(x,y,r)'

    def __init__(self, x=0, y=0, r=1):
        self._r = r
        self._x = x
        self._y = y

    def __repr__(self):
        return 'Circle({},{},{})'.\
               format(self.getx(), self.gety(),\
                      self.getr())

    #silly, but has a point: str can be different from repr
    def __str__(self):
        return 'hello world'

    def __contains__(self, item):
        'point in circle'

        px, py = item
        return (self.getx() - px)**2 + \
               (self.gety() - py)**2 < self.getr()**2

    def getr(self):
        'radius'

        return self._r

    def getx(self):
        'x'
        self._lst.append(self._x)
        return self._x


    def gety(self):
        'y'
        self._lst.append(self._y)
        return self._y

    def setr(self,r):
        'set r'
        self._r = r

    def setx(self,x):
        'set x'
        self._x = x

    def sety(self,y):
        'set y'
        self._y = y
    def move(self,x,y):
        self._x += x
        self._y += y
    def concentric(self, d):
        d = self._list
    def area(self):
        'area of circle'

        return (self.getr())**2*pi

    def circumference(self):
        'circumference of circle'
        return 2*self.getr()*pi

我的问题措辞有点笨拙,但我想做的是检查 2 个不同的圆圈是否具有相同的中心(x,y) 我认为解决这个问题的最简单方法是将 2 个点输入到一个列表中,但我不知道如何比较这 2 个列表,因为每次我尝试我的代码时,它都会将所有内容添加到同一个列表中

将以下方法添加到您的Circle类。

def equal_center(self, other):
    'check if another circle has same center'
    return (self._x == other._x) & (self._y == other._y)

用法

C1 = Circle(3, 5, 8)
C2 = Circle(3, 5, 10)
C3 = Circle(3, 2, 1)

C1.equal_center(C2)  # True
C1.equal_center(C3)  # False

我建议创建一个函数,它接受两个圆对象并通过比较每个对象的xy值来返回坐标是否相同:

def same_center(circle_1, circle_2):
  if circle_1.getx() == circle_2.getx() and circle_1.gety() == circle_2.gety():
    return True
  else:
    return False

此解决方案比使用列表容易得多,并且应该易于实现。

如果你有两个类的实例......

a = Circle(0,0,1)
b = Circle(0,0,1)

您可以将它们添加到圈子列表中...

circles = [a,b]

并遍历列表,检查它们的值......

for i in circles:
    for j in filter(lambda x  : x != i, circles):
        if i._x == j._x and i._y == j._y:
            return True #two circles have same center

这应该适用于该类的 n 个实例,但如果您只想检查它的两个

if a._x == b._x and a._y == a._y:
   return True

暂无
暂无

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

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