Python IF多个“和”“或”在一个语句中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36298231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:42:36  来源:igfitidea点击:

Python IF multiple "and" "or" in one statement

pythonpython-2.7python-3.xif-statement

提问by yingnan liu

I am just wondering if this following if statement works:

我只是想知道以下 if 语句是否有效:

    value=[1,2,3,4,5,f]
    target = [1,2,3,4,5,6,f]
    if value[0] in target OR value[1] in target AND value[6] in target:
       print ("good")

My goal is to make sure the following 2 requirements are all met at the same time: 1. value[6] must be in target 2. either value[0] or value[1] in target Apologize if I made a bad example but my question is that if I could make three AND & OR in one statement? Many thanks!

我的目标是确保同时满足以下 2 个要求: 1. value[6] 必须在目标中 2. 目标中的 value[0] 或 value[1] 如果我做了一个坏例子,请道歉,但是我的问题是,如果我能在一个语句中做三个 AND & OR 吗?非常感谢!

回答by alecxe

Use parenthesisto group the conditions:

使用括号对条件进行分组:

if value[6] in target and (value[0] in target or value[1] in target):

Note that you can make the inlookups in constant time if you would define the targetas a set:

请注意,in如果将 定义target为集合,则可以在恒定时间内进行查找:

target = {1,2,3,4,5,6,f}


And, as mentioned by @Pramod in comments, in this case value[6]would result in an IndexErrorsince there are only 6 elements defined in valueand indexing is 0-based.

而且,正如@Pramod 在评论中提到的,在这种情况下value[6]会导致 an,IndexError因为只有 6 个元素被定义value并且索引是基于 0 的。