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

标签 python lambda

我有以下 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/

相关文章:

node.js - 如何在无服务器框架上包含静态文件?

c# - 使用自定义 FluentValidator 验证器验证枚举

java - 如何从 ifPresentOrElse 语句中获取对象数据?

c# - 添加到 Lambda 表达式并使用 Entity Framework

python - 除了使用系统 ping 实用程序或发送 ICMP 数据包来创建网络状态监视器之外,还有其他选择吗?

python - 如何使用 corenlp 用 python 提取句法特征?

python - 添加分数类 python

python - 值错误 : dictionary update sequence element #0 has length 1; 2 is required

python - Django model.foreignKey 并返回 self.text 错误

java - 如何使用 java 将最后 10 个最新文件保留在目录中?