gpt4 book ai didi

Python lambda使用for循环动态添加参数

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:09 24 4
gpt4 key购买 nike

我有以下 lambda 表达式:

constraints = lambda values: (
values['volume'] < 10,
values['mass'] < 100,
values['nItems'] <= 10,
values['nItems'] >= 5
)

我有一个包含品牌(动态填充)的列表,例如

brands = ['nestle', 'gatorate'] 

我希望能够动态地添加额外的表达式:

constraints = lambda values: (
values['volume'] < 10,
values['mass'] < 100,
values['nItems'] <= 10,
values['nItems'] >= 5,

#dynamically adds these parameters
values['nestle'] < 5,
values['gatorate'] < 5
)

我如何使用 for 循环遍历品牌并动态地将其他参数填充到 brands 列表中的constraints 中?

答案可以是任何形式,只要我能得到想要的约束函数。

最佳答案

首先,不要在不需要的地方使用lambda

PEP8

Always 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

关于Python lambda使用for循环动态添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37878794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com