I have two boolean lists, e.g.,
x=[True,True,False,False]
y=[True,False,True,False]
I want to AND these lists together, with the expected output:
xy=[True,False,False,False]
I thought that expression x and y
would work, but came to discover that it does not: in fact, (x and y) != (y and x)
Output of x and y
: [True,False,True,False]
Output of y and x
: [True,True,False,False]
Using list comprehension does have correct output. Whew!
xy = [x[i] and y[i] for i in range(len(x)]
Mind you I could not find any reference that told me the AND operator would work as I tried with x and y. But it's easy to try things in Python.
Can someone explain to me what is happening with x and y
?
And here is a simple test program:
import random
random.seed()
n = 10
x = [random.random() > 0.5 for i in range(n)]
y = [random.random() > 0.5 for i in range(n)]
# Next two methods look sensible, but do not work
a = x and y
z = y and x
# Next: apparently only the list comprehension method is correct
xy = [x[i] and y[i] for i in range(n)]
print 'x : %s'%str(x)
print 'y : %s'%str(y)
print 'x and y : %s'%str(a)
print 'y and x : %s'%str(z)
print '[x and y]: %s'%str(xy)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…