【发布时间】:2011-12-13 07:14:25
【问题描述】:
假设我有一个
class Rectangle(object):
def __init__(self, length, width, height=0):
self.l = length
self.w = width
self.h = height
if not self.h:
self.a = self.l * self.w
else:
from itertools import combinations
args = [self.l, self.w, self.h]
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
# original code:
# (self.l * self.w * 2) + \
# (self.l * self.h * 2) + \
# (self.w * self.h * 2)
self.v = self.l * self.w * self.h
大家对第 12 行有什么看法?
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
我听说应该避免显式的列表索引引用。
有没有我可以使用的函数,其作用类似于sum(),但仅用于乘法?
感谢大家的帮助。
【问题讨论】:
-
FWIW,您也可以将“* 2”排除在总和之外。
-
好电话。我改了。