首先,不要在不需要的地方使用lambdaAlways use a def statement instead of an assignment statement that
binds a lambda expression directly to an identifier.
Yes:
def f(x): return 2*x
No:
f = lambda x: 2*x
The first form means that the name of the resulting function object is
specifically 'f' instead of the generic ''. This is more
useful for tracebacks and string representations in general. The use
of the assignment statement eliminates the sole benefit a lambda
expression can offer over an explicit def statement (i.e. that it can
be embedded inside a larger expression)
列出功能列表
现在来解决这个问题。列一个函数的列表来检查你的值。在
更新列表意味着更新约束。在def _constrain_main(values):
"""Static constraints"""
return (values['volume'] < 10 and values['mass'] < 100 and
values['nItems'] <= 10 and values['nItems'] >= 5)
def constrain(values):
"""Check for all constraints"""
return all(c(values) for c in constraints)
# list of constraints
constraints = [_constrain_main]
# example
values = {
'volume': 8,
'mass': 80,
'nItems': 8,
'nestle': 6,
'gatorate': 6,
}
print(constrain(values)) # True
# now append other lambdas (lambda is desired here)
constraints.append(lambda values: values['nestle'] < 5)
constraints.append(lambda values: values['gatorate'] < 5)
print(constrain(values)) # False