python-3.x 一个列表解析可以同时用于方法和类吗?

xfyts7mz  于 2023-03-20  发布在  Python
关注(0)|答案(2)|浏览(139)

我有一个简单的程序,可以根据预设值确定金字塔的侧面面积和体积:

class RightSquarePyramid():
    def __init__(self, b=0, h=0):
        self.b = float(b)
        self.h = float(h)
        pass
    
    def slantHeight(self):
        self.l = sqrt((self.h ** 2 + (self.b / 2) ** 2))
        return self.l
    
    def lateralSurfaceArea(self):
        return 2 * self.b * self.l
    
    def volume(self):
        return 1/3 * self.b ** 2 * self.h

myList = [[2.5, 5.0], [4.3, 2.5], [8, 3]]

tri0, tri1, tri2 = [RightSquarePyramid(*x) for x in myList]
tri0.slantHeight()
tri1.slantHeight()
tri2.slantHeight()
print(round(tri0.lateralSurfaceArea(), 3), round(tri1.lateralSurfaceArea(), 3), round(tri2.lateralSurfaceArea(), 3))
print(round(tri0.volume(), 3), round(tri1.volume(), 3), round(tri2.volume(), 3))

发生这种情况是因为我们只有底座的高度和长度,所以我们需要先计算倾斜高度。
我目前正在使用此解决方案:

tri0, tri1, tri2 = [RightSquarePyramid(*x) for x in myList]
triForce = tri0, tri1, tri2
[x.slantHeight() for x in triForce]
# tri0.slantHeight()
# tri1.slantHeight()
# tri2.slantHeight()
print(round(tri0.lateralSurfaceArea(), 3), round(tri1.lateralSurfaceArea(), 3), round(tri2.lateralSurfaceArea(), 3))
print(round(tri0.volume(), 3), round(tri1.volume(), 3), round(tri2.volume(), 3))

但这实际上是用2行代码替换了3行代码。
有没有一种方法可以同时对RightSquarePyramid()slantHeight()使用列表解析?也许我刚才忽略的一个公共变量可以做到这一点?

xhv8bpkk

xhv8bpkk1#

你可以在枚举所有三个tri变量的所有情况下使用循环,没有理由一开始就把列表分解成这三个变量。
如果你想执行一个副作用的代码而不是对它的返回值做一些事情,那么编写循环的惯用方法是把它放在一个for循环中,而不是列表解析中(列表解析只会给予你一个你不想要的值的列表,可能是None s)。
对于print情况,可以使用生成器表达式和*运算符将迭代结果作为参数传递给函数。

triForce = [RightSquarePyramid(*x) for x in myList]
for t in triForce:
    t.slantHeight()

print(*(round(t.lateralSurfaceArea(), 3) for t in triForce))
print(*(round(t.volume(), 3) for t in triForce))

由于您使用类的两个不同方法执行完全相同的print例程,因此您甚至可以将它们放在另一个循环中:

for f in (
    RightSquarePyramid.lateralSurfaceArea,
    RightSquarePyramid.volume
):
    print(*(round(f(t), 3) for t in triForce)))
mspsb9vt

mspsb9vt2#

感谢@Samwise和@Kaya3的意见,我相信我已经解决了这个问题,下面是代码:

from math import sqrt

class RightSquarePyramid():
    def __init__(self, b=0, h=0):
        self.b = float(b)
        self.h = float(h)
        pass
    
    def slantHeight(self):
        return sqrt((self.h ** 2 + (self.b / 2) ** 2))
         
    
    def lateralSurfaceArea(self):
        self.l = self.slantHeight()
        return 2 * self.b * self.l
    
    def volume(self):
        return 1/3 * self.b ** 2 * self.h
    
myList = [[2.5, 5.0], [4.3, 2.5], [8, 3]]

triForce = [RightSquarePyramid(*x) for x in myList]
for f in (
    RightSquarePyramid.lateralSurfaceArea,
    RightSquarePyramid.volume
):
    print(*(round(f(t), 3) for t  in triForce))

相关问题