首页 > 解决方案 > 尝试调用函数的特定名称

问题描述

我现在感觉很愚蠢。

一旦输入了特定名称,我一直试图让我的函数运行一些代码。

我觉得我正在整理的代码很幼稚,我目前正试图为我做错的事情寻求一些帮助。任何输入表示赞赏。我为我凌乱的代码道歉。

我想简单地让我的函数参数(cond)能够运行这个特定的代码,如果它便宜,大屏幕或苹果产品。感谢你的帮助 :)

def 满足(产品,条件):

inexpensive = (4, '<=', 1000)
large_screen = (2, '>=', 6.3)
apple_product = (1, '==', 'Apple')

conditions = (inexpensive, large_screen, apple_product)

if cond == conditions[0]:
    if cond[1] == '<=':
        return True if cond[2] <= product[4] else False
    elif cond[1] == '<=':
        return True if cond[2] <= product[4] else False
    elif cond[1] == '==':
        return True if cond[2] == product[4] else False

if cond == conditions[1]:
    if cond[1] == '<=':
        return True if cond[2] <= product[4] else False
    elif cond[1] == '<=':
        return True if cond[2] <= product[4] else False
    elif cond[1] == '==':
        return True if cond[2] == product[4] else False

if cond == conditions[2]:
    if cond[1] == '==':
        return True if cond[2] == product[1] else False

输入:产品功能列表(product() 和条件(cond),如上指定。输出:如果 cond 对产品成立,则为 True,否则为 False。

调用 satisfies(['Nova 5T', 'Huawei', 6.26, 3750, 497], 便宜) 应该返回 True。

标签: python

解决方案


您可以通过以下方式简化代码

  • 将其拆分为两个功能:
    • 检查单个条件的
    • 另一个使用组合函数检查许多;默认为all(), 表示“与”;如果需要,您可以使用combinator=any“OR”类型的查询)。
  • 使用该operator模块,其中包含各种运算符的谓词函数,以及运算符字符串到这些函数的映射
import operator

operators = {
    "<=": operator.le,
    ">=": operator.ge,
    "==": operator.eq,
    "!=": operator.ne,
    "<": operator.lt,
    ">": operator.gt,
}


def check_condition(product, cond):
    field, operator, value = cond
    return operators[operator](product[field], value)


def check_conditions(product, conditions, combinator=all):
    return combinator(
        check_condition(product, cond)
        for cond in conditions
    )


def check_products_conditions(products, conditions, combinator=all):
    return [
        product 
        for product in products 
        if check_conditions(product, conditions, combinator=combinator)
    ]


inexpensive = (4, "<=", 1000)
large_screen = (2, ">=", 6.3)
apple_product = (1, "==", "Apple")

product = ['Nova 5T', 'Huawei', 6.26, 3750, 497]

# Check single condition
check_condition(
    product,
    inexpensive,
)

# Check multiple conditions
check_conditions(
    product,
    conditions=(
        inexpensive,
        large_screen,
        apple_product,
    ),
)

# Check multiple products against multiple conditions
matching_products = check_products_conditions(
    products=[product, product, product],
    conditions=(
        inexpensive,
        large_screen,
        apple_product,
    ),
)

推荐阅读