【问题标题】:Python 3 order of testing undeterminedPython 3 的测试顺序未确定
【发布时间】:2011-06-10 11:31:47
【问题描述】:
string='a'
p=0
while (p <len(string)) & (string[p]!='c') :
                    p +=1

print ('the end but the  process  already died ')
       while (p <1) & (string[p]!='c') :
IndexError: string index out of range

我想测试一个直到字符串结尾的条件(例如字符串长度=1) 为什么这两个部分的和执行的是条件已经是假的! 只要p &lt; len(string)。第二部分甚至不需要执行。 如果它确实有很多性能可能会丢失

【问题讨论】:

  • 你为什么使用按位&amp; 运算符?
  • 这不是一些重新发明轮子的代码。 p = string.find(c) 怎么样(如果不存在则返回 -1 而不是 len(string)-1 - 所以它更好,如 in,而不是模棱两可)?

标签: python comparison python-3.x boolean


【解决方案1】:

按位与,“a & b”,应该被认为是

function _bitwise_and(A,B):
    # A and B are Python expressions
    #   which result in lists of 1's and 0's

    a = A.evaluate()
    b = B.evaluate()

    return [ 1 if abit==1 and bbit==1 else 0 for abit,bbit in zip(a,b)]

所以,以图形方式,

a:   ...  0 1 1 0
b:   ...  1 0 1 0
         --------
a&b  ...  0 0 1 0   <- each bit is 1 if-and-only-if the
                       corresponding input bits are both 1

结果是一个位列表,打包成一个整数。

.

逻辑与,“a 和 b”,应该被认为是

function _and(A,B):
    # A and B are Python expressions which result in values having truthiness

    a = A.evaluate()
    if is_truthy(a):
        b = B.evaluate()
        return b
    else:
        return a

.

注意:如果 A 的结果是假的,B 永远不会被计算 - 所以如果表达式 B 在计算时出错,按位与将导致错误,而 逻辑与不会

这是Python常用习语的基础,

while (offset in data) and test(data[offset]):
    do_something_to(data[offset])
    next offset

... 因为 data[offset] 仅在 offset 是可用(不产生错误)值时才被评估。

通过使用“&”而不是“and”,您可以通过在循环结束时评估 data[last_offset+1] 来保证错误。

.

当然,这可以用另一种常见的习语来避免:

for ch in string if ch=='c':
    do_something_to(ch)

这完全避免了 IndexError 问题。

【讨论】:

    【解决方案2】:

    您需要使用boolean operators and and or 而不是按位运算符 & 和 |

    【讨论】:

      【解决方案3】:

      您没有使用正确的布尔值and。使用它,你不会看到这个问题。您正在使用的 (&amp;) 是按位比较,它评估双方。

      【讨论】:

        猜你喜欢
        • 2012-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-01
        • 2015-06-12
        • 2020-04-17
        相关资源
        最近更新 更多