Python IF多个“和” "或"在一个声明中 [英] Python IF multiple "and" "or" in one statement

查看:155
本文介绍了Python IF多个“和” "或"在一个声明中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just wondering if this following if statement works:

    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")

我的目标是确保以下2个要求是所有人都在同一时间遇到:
1.值[6]必须在目标
2.目标
中的值[0]或值[1]如果我做了一个坏的例子,请道歉但我的问题是,如果我可以制作三个AND&还是在一个声明中?非常感谢!

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!

推荐答案

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

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

请注意,如果要定义<$,可以在查找中以查找。 c $ c> target 作为一组:

Note that you can make the in lookups in constant time if you would define the target as a set:

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






并且,as @Pramod在评论中提到,在这种情况下 value [6] 会导致 IndexError ,因为只有6在中定义的元素,索引从0开始。


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

这篇关于Python IF多个“和” &QUOT;或&QUOT;在一个声明中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆