嵌套条件语句的可读性

2024-06-27 20:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在用Python编写一个程序来为射影几何建模,而投影点的同余函数看起来相当讨厌。在

(对于任何感兴趣的人,如果两个投影点都位于穿过原点的一条直线上,则它们是全等的。)

class Point(object):
    def __init__(self, a, b, c):
        self.coords = [ a, b, c ]

    def congruent(self, other):
        ratio = 0
        for i in range(3):
            if self.coords[i] != 0 and other.coords[i] != 0:
                if ratio is 0:
                    ratio = other.coords[i] / self.coords[i]
                elif ratio != other.coords[i] / self.coords[i]:
                    return False
            elif self.coords[i] != 0 or other.coords[i] != 0:
                return False
        return True

我是Python新手,但我知道通常有一种“Python”方法来完成所有事情。考虑到这一点,我该如何使它更具可读性?在


Tags: self程序falsereturnifdefcoords建模
3条回答

可能使用if self.coords[i]代替if self.coords[i] != 0(类似的例子也是如此),用if not ratio代替{}。在Python中,任何非零值都会传递if子句,因此不需要检查它是否为非零,它是自动的。在

def congurent(self,other):
    ratio = None
    for a,b in zip(self,other):
        if a != 0 and b != 0:
            if ratio is None: 
                 ratio = a/float(b)
            elif abs(ratio - a/float(b))>0.001:
                 return False
        elif a!=0 or b!=0:
            return False
     return True

可能有点像Python。。。虽然它真正的变化是如何迭代列表(它的行数相同)

这个怎么样:

def congruent(self, other, eps=0.001):
    ratios = (c1 / c2 for c1, c2 in zip(self.coords, other.coords) if c1 or c2)
    try:
        first = next(ratios)
        return all(abs(ratio - first) < eps for ratio in ratios)
    except ZeroDivisionError:
        return False
  1. 如果可能,更喜欢直接在元素上操作而不是在索引上操作(zip很方便)。在
  2. 或者坐标为非零时,list comprehension得到所有的坐标比。如果两者都是,那就好了,而且会被排除在外。在
  3. ZDE只在c1非零且c2为零时发生,因此这是一个失败。在
  4. 最后,如果所有比率相等,我们就通过了。在

注意:如果不使用Python3,应该在文件顶部添加from __future__ import division,这样就不会得到整数坐标值的错误结果。在

编辑:根据@JoranBeasley添加了短路和epsilon比较。在

相关问题 更多 >