Python中的运算符不起作用 [英] Python in operator is not working

查看:197
本文介绍了Python中的运算符不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行这个代码时,什么也没有显示出来。例如,我调用 ind(1,[1,2,3]),但我没有得到整数 13 if(e in)

def ind L == True):
print('13')
else:
print('12')


解决方案

运算符优先级。如果您在L 附近放置,将工作:

pre $ code def def(e,L):
if((e in L)== True) :
print('13')
else:
print('12')

ind(1,[1,2,3])

但是可以完成 True 的测试通常成语)没有真正

  def ind(e,L ):
if(e in L):
print('13')
else:
print('12')

ind(1 ,[1,2,3])

编辑:作为奖励,您甚至可以使用 True False 来保留/取消操作。用你的例子:

  def ind(e,L):
print('13'*(e in L ),或'12')

ind(1,[1,2,3])

ind(4,[1,2,3])

这个输出:

  13 
12

因为 code>首先被评估为 True 并且 13 * True 是 13 。不查找布尔表达式的第二部分。



但是当用 4 调用函数时,则发生以下情况:

 `13` *(e in L)or '12` - > `13` *假或'12' - > ''或'12' - > 12 

空字符串计算结果为 False 因此返回布尔表达式的第二部分。


When I run this code, nothing shows up. For example I call ind(1, [1, 2, 3]), but I don't get the integer 13.

def ind(e, L):
    if (e in L == True):
        print('13')
    else: 
        print('12')

解决方案

Operator precedence. If you put ( and ) around e in L it will work:

def ind(e, L):
    if ((e in L) == True):
        print('13')
    else:
        print('12')

ind(1, [1, 2, 3])

But testing for True can be done (and is the usual idiom) done without the True

def ind(e, L):
    if (e in L):
        print('13')
    else:
        print('12')

ind(1, [1, 2, 3])

Edit: as a bonus you can even use True and False to keep/nullify things. With your example:

def ind(e, L):
    print('13' * (e in L) or '12')

ind(1, [1, 2, 3])

ind(4, [1, 2, 3])

And this ouputs:

13
12

Because e in L has first been evaluated to True and 13 * True is 13. The 2nd part of the boolean expression is not looked up.

But when calling the function with 4, then the following happens:

`13` * (e in L) or '12` -> `13` * False or '12' -> '' or '12' -> 12

Becase and empty string evaluates to False too and therefore the 2nd part of the or boolean expression is returned.

这篇关于Python中的运算符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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