Booleans list for Python gives strange results

I'm trying to:

[True,True,False] and [True,True,True] 

and get [True, True True]

but

 [True,True,True] and [True,True,False] 

gives

 [True,True,False] 

Not too sure why it gives these strange results, even after looking at some other python buffer related issues. Integer does the same (replace True β†’ 1 and False β†’ 0 above and the results will be the same). What am I missing? I obviously want

 [True,True,False] and [True,True,True] 

for rate

 [True,True,False] 
+4
source share
7 answers

Others explained what was happening. Here are some ways to get what you want:

 >>> a = [True, True, True] >>> b = [True, True, False] 

Use listcomp:

 >>> [ai and bi for ai,bi in zip(a,b)] [True, True, False] 

Use the and_ function with map :

 >>> from operator import and_ >>> map(and_, a, b) [True, True, False] 

Or my preferred method (although this requires numpy ):

 >>> from numpy import array >>> a = array([True, True, True]) >>> b = array([True, True, False]) >>> a & b array([ True, True, False], dtype=bool) >>> a | b array([ True, True, True], dtype=bool) >>> a ^ b array([False, False, True], dtype=bool) 
+4
source

Any populated list is rated True . True and x creates x , the second list.

+5
source

From the Python documentation :

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is computed and the return value is returned.

Received second return value.

PS I’ve never seen this behavior before, I had to look for it myself. My naive expectation was that a Boolean expression would give a logical result.

+5
source

[True, True, False] evaluates to logical (due to the and operator) and evaluates to True because it is nonempty. Same thing with [True, True, True] . The result of any statement is what comes after the and operator.

You can do something like [ai and bi for ai, bi in zip(a, b)] for lists a and b .

+1
source

As far as I know, you need to scroll through the list. Try making a list of this kind:

 l1 = [True,True,False] l2 = [True,True,True] res = [ x and y for (x,y) in zip(l1, l2)] print res 
+1
source

and returns the last element if they are all evaluated to True .

 >>> 1 and 2 and 3 3 

The same is true for lists that evaluate to True if they are not empty (as in your case).

0
source

Python works by shorting its Boolean and giving the result as a result. The populated list evaluates to true and gives the result as the value of the second list. Look at this when I just changed the position of your first and second list.

 In [3]: [True,True,True] and [True, True, False] Out[3]: [True, True, False] 
0
source

Source: https://habr.com/ru/post/1439847/


All Articles