[英]Is there any way that I can turn this into a list comprehension
我经常发现自己做这样的低效循环:
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语句类型而已。 顺便说一下,这是元组的子类,其中add运算符将类似的索引值相加,例如(1, 2, 3) + (4, 5, 6, 7) == (5, 7, 9, 7)
。 我认为filter()
可以帮助我解决这个问题,但是我不确定如何实现。
编辑:这是针对Python 3。
我不确定是否能完全理解它,但我认为stdlib是您的朋友:
from itertools import izip_longest
dimensions = []
for a, b in izip_longest(self, other, fillvalue=0):
dimensions.append(a + b)
我认为列表理解不会很干净。
这是使用列表理解的简单方法,尽管恕我直言很丑。
dimensions = [
sum(map(lambda x: ((x is None) and 1 or 2) - 1, (
self[i] if i<self.numberOfDimensions else None,
other[i] if i<other.numberOfDimensions else None
)))
for i in range(max(self.numberOfDimensions, other.numberOfDimensions))
]
最简洁的方法是
map(sum, itertools.izip_longest(self, other, fillvalue=0))
要么
itertools.starmap(operator.add,
itertools.izip_longest(self, other, fillvalue=0))
这可以完成您认为原始代码应该执行的操作。 如果您使用的是Python 3,请将结果转换为元组或列表或任何您想要的结果。
怎么样,尽管未经测试:
dimensions = [sum(map(lambda x: ((x is None) and 1 or 2) - 1, (self[i] if i < self.numberOfDimensions else None, other[i] if i < other.numberOfDimensions else None))) for i in range(max(self.numberOfDimensions, other.numberOfDimensions))]
我认为您需要的缺失部分是:
(a,b) = (self[i] if i < self.numberOfDimensions else None, other[i] if i < other.numberOfDimensions else None)
当然,我不相信单个表达式会更具可读性。 使用某种类型的地图先生成(a,b)
可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.