Python懒惰字典评估
作者:互联网
Python传播者会说Python没有switch语句的原因是因为它有字典.那么……我怎么能用字典来解决这个问题呢?
问题是所有值都在评估中,并根据输入提出异常.
这只是一个存储数字或数字列表并提供乘法的类的一个愚蠢的例子.
class MyClass(object):
def __init__(self, value):
self._value = value
def __mul__(self, other):
return {
(False, False): self._value * other._value ,
(False, True ): [self._value * o for o in other._value] ,
(True , False): [v * other._value for v in self._value] ,
(True , True ): [v * o for v, o in zip(self._value, other._value)],
}[(isinstance(self._value, (tuple, list)), isinstance(other._value, (tuple, list)))]
def __str__(self):
return repr(self._value)
__repr__ = __str__
>>> x = MyClass(2.0)
>>> y = MyClass([3.0, 4.0, 5.0])
>>> print x
2.0
>>> print y
[3.0, 4.0, 5.0]
>>> print x * y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __mul__
TypeError: can't multiply sequence by non-int of type 'float'
我可以解决它的一种方法是为每个值添加“lambda:”前缀,并在字典查找后调用lambda函数….“}(isinsta …)”
有没有更好的办法?
解决方法:
是的,为这些不同的选项定义小lambdas:
def __mul__(self, other):
scalar_times_scalar = lambda x,y: x*y
scalar_times_seq = lambda x,y: [x*y_i for y_i in y]
seq_times_scalar = lambda x,y: scalar_times_seq(y,x)
seq_times_seq = lambda x,y: [x_i*y_i for x_i,y_i in zip(x,y)]
self_is_seq, other_is_seq = (isinstance(ob._value,(tuple, list))
for ob in (self, other))
fn = {
(False, False): scalar_times_scalar,
(False, True ): scalar_times_seq,
(True , False): seq_times_scalar,
(True , True ): seq_times_seq,
}[(self_is_seq, other_is_seq)]
return fn(self._value, other._value)
当然,理想情况下,您只能在类或模块范围内定义这些lambda.为了便于参考,我在这里用__mul__方法展示了它们.
标签:python,dictionary,lazy-evaluation,switch-statement 来源: https://codeday.me/bug/20190827/1739667.html