比较if语句中的多个值 [英] Compare to multiple values in an if statement

查看:131
本文介绍了比较if语句中的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将需要多个if语句来与相同的几个元素进行比较,并且想知道是否有这些方法可以使代码更简洁,更容易.

im going to need multiple if statements comparing to the same couple elements, and was wondering if there was something along these lines i could do to make the code cleaner and easier.

示例将是该功能.

def test(num): 

    a = [1, 2, 3]

    if num == a : 
        return True

    else : 
        return False

会返回

>>>test(1)
True
>>>test(2)
True
>>>test(5)
False

不必为123编写单独的if语句.

Instead of having to write the separate if statements for 1, 2, and 3.

推荐答案

使用in运算符

if num in a : 

def test(num): 
    a = [1, 2, 3]
    if num in a : 
        return True
    else : 
        return False

可以解决(如Padraic所建议的那样)

a work around would be (as suggested by Padraic)

 def test(num): 
        a = [1, 2, 3]
        return num in a

之所以可行,是因为in运算符比较RHS中是否存在LHS并分别返回布尔值.

This would work because, The in operator compares if the LHS is present in the RHS and returns a boolean value respectively.

这也是可能的

test = lambda x:  num in [1, 2, 3]

这一切都在一行中!

这篇关于比较if语句中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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