[英]How to compare integers with accuracy in Python?
我有一個顏色元組。 例如,(218、174、84)。 任務是將每個紅色、綠色和藍色值增加一些增量,然后將其與精度 1 進行比較。如何以Pythonic 方式執行此操作? 你知道最佳實踐嗎?
顏色:(218, 174, 84) 增量:5
對於紅色值 222、223、224 是合法的。 綠色:178、179、180,藍色:88、89、90。
def valid_color(orig_color, new_color, increment):
return all(c1 + increment - 1 <= c2 <= c1 + increment + 1 for c1, c2 in zip(orig_color, new_color))
使用zip()
將原始顏色的組件與您要比較的顏色配對。 然后使用比較運算符來測試每個組件是否有效。
如果你想使用 python 魔法並只使用==
,你可以這樣做:
class Color(tuple):
def __init__(self, *_, inc=0):
self.inc = inc
def __eq__(self, other):
return all(c1 + self.inc - 1 <= c2 <= c1 + self.inc + 1 for (c1, c2) in zip(self, other))
c = Color((1, 2, 3), inc=5)
c2 = Color((5, 6, 8))
print(c == c2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.