在IF语句中使用OR比较 [英] Using OR comparisons with IF statements
问题描述
在Python中使用IF语句时,必须执行以下操作才能使层叠"正常工作.
When using IF statements in Python, you have to do the following to make the "cascade" work correctly.
if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
在检查等于"时是否有一种方法可以使Python接受多个值?例如,
Is there a way to make Python accept multiple values when checking for "equals to"? For example,
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
运算符检查左侧项目是否出现在右侧手柄元组内部.
The values in parentheses are a tuple. The in
operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.
请注意,当Python使用in
运算符搜索元组或列表时,它将进行线性搜索.如果右侧有大量物品,则可能是性能瓶颈.更大范围的方法是使用 frozenset
:
Note that when Python searches a tuple or list using the in
operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a frozenset
:
AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
if job in AwesomeJobs:
print "awesome"
如果在程序运行期间不需要更改很棒的作业列表,则首选使用frozenset
而不是set
.
The use of frozenset
over set
is preferred if the list of awesome jobs does not need to be changed during the operation of your program.
这篇关于在IF语句中使用OR比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!