使用 OR 与 IF 语句进行比较 [重复]
-
02-07-2019 - |
题
这个问题在这里已经有答案了:
- 如何针对一个值测试多个变量? 21 个答案
在Python中使用IF语句时,必须执行以下操作才能使“级联”正常工作。
if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
有没有办法让Python在检查“等于”时接受多个值?例如,
if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
解决方案
if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
括号中的值是一个元组。这 in
运算符检查左侧项是否出现在右侧句柄元组内的某个位置。
请注意,当 Python 使用以下命令搜索元组或列表时 in
运算符,它进行线性搜索。如果右侧有大量项目,这可能会成为性能瓶颈。更大规模的方法是使用 frozenset
:
AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
if job in AwesomeJobs:
print "awesome"
指某东西的用途 frozenset
超过 set
如果在程序运行期间不需要更改很棒的作业列表,则首选。
其他提示
您可以使用在:
if job in ["mechanic", "tech"]:
print "awesome"
当检查非常大的数字时,也可能值得存储一组要检查的项目,因为这样会更快。例如。
AwesomeJobs = set(["mechanic", "tech", ... lots of others ])
...
def func():
if job in AwesomeJobs:
print "awesome"
if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
虽然我不认为你可以直接做你想做的事,但一种选择是:
if job in [ "mechanic", "tech" ]:
print "awesome"
elif job in [ "tool", "rock" ]:
print "dolt"
具有常量项的元组本身作为常量存储在编译函数中。它们可以用一条指令加载。另一方面,列表和集合总是在每次执行时重新构造。
元组和列表都使用线性搜索来查找内部运算符。Sets 使用基于哈希的查找,因此对于更多数量的选项来说速度会更快。
在其他语言中,我会使用 switch/select 语句来完成工作。 你也可以在 python 中做到这一点.
不隶属于 StackOverflow