我有一个简单的程序,可以根据预设值确定金字塔的侧面面积和体积:
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()
使用列表解析?也许我刚才忽略的一个公共变量可以做到这一点?
2条答案
按热度按时间xhv8bpkk1#
你可以在枚举所有三个
tri
变量的所有情况下使用循环,没有理由一开始就把列表分解成这三个变量。如果你想执行一个副作用的代码而不是对它的返回值做一些事情,那么编写循环的惯用方法是把它放在一个
for
循环中,而不是列表解析中(列表解析只会给予你一个你不想要的值的列表,可能是None
s)。对于
print
情况,可以使用生成器表达式和*
运算符将迭代结果作为参数传递给函数。由于您使用类的两个不同方法执行完全相同的
print
例程,因此您甚至可以将它们放在另一个循环中:mspsb9vt2#
感谢@Samwise和@Kaya3的意见,我相信我已经解决了这个问题,下面是代码: