python - 输入带有比较运算符的字符串,并在数组索引上执行比较
问题描述
所以这是我到目前为止的代码:
# 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 语句,尽管我不确定它的效率如何。
希望我说清楚了。谢谢!
解决方案
对于此类问题,有两个非常有用的概念,标准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
推荐阅读
- php - 使用 MySQL 8 的 RHEL 7 上的 PHPMyAdmin 登录错误 - mysqli_real_connect():服务器发送的字符集 (255) 对客户端未知
- ruby - 上传照片API
- angularjs - 我想使用 angularjs 在 Outlook 上发送会议邀请
- c - 如何知道我应该定义哪个值 _POSIX_C_SOURCE?
- spring - Spring Boot + Web + Thymeleaf:Spring IO Guide for "Securing a Web Application" 中的圆形视图路径
- android - android gradle - google services plugin 3.3.0 error of " For input string: " 12" - 如何解决?
- css - 将文本左对齐(相对于)div
- java - 在二维数组中搜索特定行
- c# - Is SNK enough to skip windows smart protect screen
- r - Converting Monthly Data to Daily in R