简体   繁体   中英

Python logical `and` returning wrong results comparing lists

y1 = [True, True, False, False]
y2 = [False, True, True, False]
y3 = y1 and y2

print(y3)
>>> [False, True, True, False]

What is going on here? the third item in the operation is False and True and this results in True ?

X and Y evalutes to:

  • X (if X is falsey )
  • Y (if X is truthy )

Any nonempty list is truthy.

So if

y1 = [True, True, False, False]

and

y2 = [False, True, True, False]

then y1 and y2 evaluates to y2 , which is [False, True, True, False] .

If you want to and individual elements of your lists, you can do it with zip and a list comprehension :

y3 = [x1 and x2 for x1,x2 in zip(y1,y2)]
x     | y     | x and y
------|-------|---------
True  | True  | y
True  | False | y
False | True  | x
False | False | x

Since a non-empty list is evaulated as True in a boolean expression in python, x and y returns y .

What you are looking for is:

y3 = [a and b for a,b in zip(y1,y2)]

when you are working with the list, this will not work as AN operators works. But if you use AND then it will return the second precedence ie if first value is True and second is False, this will return False and If first value is False and second value is True that will return True. Similarly, that is what is happening in your code.If you use "OR" it will return the first precedence ie y1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM