首页 > 解决方案 > 输入带有比较运算符的字符串,并在数组索引上执行比较

问题描述

所以这是我到目前为止的代码:

# Function to search for possible matches for words: and chapters:
def intSearch(term, row, index):
    """
    Index of 6: Word search
    Index of 7: Chapter search
    """
    rowValue = row[index]
    if True:
        return True
    return False

“如果为真”只是暂时的。所以我想要的是术语输入是一个比较运算符,然后是一个整数,例如'> = 334'。然后可以将该字符串分解并与我可以使用 row[index] 的行的特定索引进行比较。如果这个比较是正确的,它将返回 True,如果不正确,它将返回 False。比较应该适用于基本上所有运算符,包括:==、!=、>、<、<=、>= 和范围。

所以比较基本上看起来像:

if row[index] >= term:

其中 row[index] 是数组整数, >= 是比较运算符, term 是要比较的数字。

我可以使用很多 if 和 else 语句,尽管我不确定它的效率如何。

希望我说清楚了。谢谢!

标签: pythonpython-3.x

解决方案


对于此类问题,有两个非常有用的概念,标准operator库和标准dictionary.

例子:

import operator as op

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

x = 10
y = 0

for op_str in op_map:
    print(f"{x} {op_str} {y}: {op_map[op_str](x, y)}")

输出:

10 == 0: False
10 != 0: True
10 > 0: True
10 < 0: False
10 <= 0: False
10 >= 0: True

推荐阅读