请考虑以下声明:
问题1:
>>> a="abc" >>> 'd' or 'e' in a 'd'有人请解释一下。 我期待一个对错......
问题2:
>>> print any(c in a for c in 'da') True这里发生了什么事 ? 如果我这样做,
>>> (c in a for c in 'da') <generator object <genexpr> at 0x011E4300>正如你所看到的,它给出了生成器对象......“任何”(方法,函数??)在这里扮演什么角色? 结果呢?
问题3:
>>> Pattern="sdfdfg" >>> if '\\'or '^' or '.' in Pattern: print "yes" else:print "no" yes这个“是”究竟是怎么回事?
告诉我一个人有光的...........
Consider the statement below:
Prob 1:
>>> a="abc" >>> 'd' or 'e' in a 'd'Someone please explain this . I was expecting a True or False ...
Prob 2:
>>> print any(c in a for c in 'da') TrueWhats happening here ? If i do this ,
>>> (c in a for c in 'da') <generator object <genexpr> at 0x011E4300>As you can see , it gives generator object...What role does 'any' (method,function ??) play here? And the result ?
Prob 3:
>>> Pattern="sdfdfg" >>> if '\\'or '^' or '.' in Pattern: print "yes" else:print "no" yesHow on earth is this "YES" ??
Show me the light someone plz...........
最满意答案
您看到的结果是or和in运算符的优先级与您预期的不同。
'd' or 'e' in a这应该被理解为'd' or ('e' in a) ,即2个操作数or是'd'和('e' in a) 。 因为d在python中被认为是真值 , or 没有查看它的下一个操作数 ,所以只返回它的第一个操作数'd' 。 请注意,这意味着or不仅仅是逻辑OR,它可以处理其他类型,并返回其他类型。
print any(c in a for c in 'da')请阅读此print any((c in a) for c in 'da') ,即,检查'da'的元素,测试该字母是否也在a ,然后查看其中任何a是否为真。 你<generator object <genexpr> at 0x011E4300>看到<generator object <genexpr> at 0x011E4300>是Python没有向你展示生成器的元素,除非它有理由跨过它们。 如果您想查看单个元素,请写:
[(c in a) for c in 'da'] if '\\'or '^' or '.' in Pattern:再次,请阅读此if ('\\' or '^') or ('.' in Pattern:) 。 由于'\\'为真,结果是正确的。
优先表
The results you are seeing are the result of the precedence of the or and in operators being different than you expect.
'd' or 'e' in aThis should be read as 'd' or ('e' in a), that is, the 2 operands to or are 'd' and ('e' in a). Since d is considered a true value in python, or doesn't look at its next operand, and just returns its first operand, 'd'. Note that this means that or isn't just a logical OR, it can deal with other types, and return other types.
print any(c in a for c in 'da')Read this print any((c in a) for c in 'da'), ie, go over the elementns of 'da', test if that letter is also in a, and then see if that held true for any of them. The reason you see <generator object <genexpr> at 0x011E4300> is that Python does not show you the elements of a generator unless it has cause to step over them. If you want to see the individual elements, write:
[(c in a) for c in 'da'] if '\\'or '^' or '.' in Pattern:Again, read this if ('\\' or '^') or ('.' in Pattern:). Since '\\' is true, the result is true.
Table of precedence
更多推荐
发布评论