python的lambda和for一起使用_Python lambda使用for循环动态添加参数

首先,不要在不需要的地方使用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


版权声明:本文为weixin_31577599原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。