python - 尝试调用函数的特定名称
问题描述
我现在感觉很愚蠢。
一旦输入了特定名称,我一直试图让我的函数运行一些代码。
我觉得我正在整理的代码很幼稚,我目前正试图为我做错的事情寻求一些帮助。任何输入表示赞赏。我为我凌乱的代码道歉。
我想简单地让我的函数参数(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。
解决方案
您可以通过以下方式简化代码
- 将其拆分为两个功能:
- 检查单个条件的
- 另一个使用组合函数检查许多;默认为
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,
),
)
推荐阅读
- javascript - 使用 jQuery 或 JavaScript 在当前视图中滚动时如何在 HTML 表中添加和删除而不影响当前视图中的元素
- c - 无法弄清楚手册中的 epoll 示例
- scala - 在 Spark 中按交替序列分组
- python - Python Pandas:遍历日期并将它们作为新行添加到数据框中?
- regex - 如何用 awk 替换 .env 文件中的值?
- sql - 从源表中获取当前 SQL 中使用的所有列的方法
- c# - 在 C# 表单中擦除图形?
- r - 如何将列表转换为数字
- angular - 我的 Angular 8 NPM 包没有找到自己的资产
- javascript - 同一行不同列(jQuery)