TypeError: unsupported operand type(s) for &: 'str' and 'int'

TypeError: unsupported operand type(s) for &: 'str' and 'int'

我正在 python 2.7 上执行以下代码片段:

i=0
j=3
a=['A','B','B','A']
while(a[i]=="A" & i<j):
    #do something

我收到了这个错误。

TypeError: unsupported operand type(s) for &: 'str' and 'int'

有什么帮助吗?

& 是 Python 中的 "bitwise and" 操作数,您应该使用 and 而不是

来自 wiki.python.org:

x & y : Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

"bitwise and" 是这样工作的:

>>> 1 & 0
0
>>> 0 & 0
0
>>> 1 & 1
1

您需要将下面的两个条件括起来。

i=0
j=3
a=['A','B','B','A']
while((a[i]=="A") & (i<j)):
    #do something

参考下面link更详细的解释 Difference between 'and' (boolean) vs. '&' (bitwise) in python. Why difference in behavior with lists vs numpy arrays?