使用比较运算符输入字符串,然后对数组索引执行比较



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

# 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

"if True"只是暂时的。因此,我希望输入项是一个比较运算符,然后是一个整数,例如'>334’。然后这个字符串可以被分解,并与我可以使用row[index]的行的特定索引进行比较。如果这个比较是正确的,它将返回True,如果不是,则返回False。该比较基本上适用于所有运算符,包括:==,!=>lt<=>=以及范围。

因此,比较基本上看起来像:

if row[index] >= term:

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

我可以使用很多if和else语句,尽管我不确定这会有多有效

希望我说清楚了。谢谢

对于这类问题有两个非常有用的概念,标准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

相关内容

最新更新