我经常发现自己在做这样的低效循环:
def __add__(self, other):
dimensions = []
for i in range(max(self.numberOfDimensions, other.numberOfDimensions)):
a = None
if i < self.numberOfDimensions:
a = self[i]
b = None
if i < other.numberOfDimensions:
b = other[i]
# Doesn't actually do the right thing here.
dimensions.append(sum(map(lambda x: ((x is None) and 1 or 2) - 1, (a, b))))
return self.__class__(dimensions)
计算很简单,它只是处理让我着迷的 if 语句类型。顺便说一句,这是元组的一个子类,其中添加运算符添加类似索引的值,如 (1, 2, 3) + (4, 5, 6, 7) == (5, 7, 9, 7)
。我认为 filter()
会帮助我解决这个问题,但我不确定如何实现它。
编辑:这是针对 Python 3 的。
最佳答案
我不确定我是否完全理解它,但我认为 stdlib 是你的 friend :
from itertools import izip_longest
dimensions = []
for a, b in izip_longest(self, other, fillvalue=0):
dimensions.append(a + b)
我不认为列表理解会很干净。
关于python - 有什么办法可以把它变成列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8990576/