[英]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
我建議創建一個函數,它接受兩個圓對象並通過比較每個對象的x
和y
值來返回坐標是否相同:
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.