Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

And/Or elemental-wise for list of bools in python

I have two lists of Bools in python:

l1 = [True, False, True]
l2 = [False, True, True]

And I wish to do elemental-wise comparison And/Or for them. I wish to get:

l3 = [False, False, True] # elemental-wise And
l4 = [True, True, True] # elemental-wise Or

So I simply put:

l3 = l1 and l2
l4 = l1 or l2

But the result behaves unexpectedly as:

l3=[False, True, True] (which is l2)
l4=[True, False, True] (which is l1)

How can I accomplish the elemental-wise comparison nice and clean?

question from:https://stackoverflow.com/questions/65859925/and-or-elemental-wise-for-list-of-bools-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use list comprehension

l3 = [(i and j) for i,j in zip(l1,l2)]
l4 = [(i or j) for i,j in zip(l1,l2)]

When you are doing

l3 = l1 and l2
l4 = l1 or l2

then it is getting reduced to

l3 = bool(l1) and l2
l4 = bool(l1) or l2

Now since l1 is non-empty list, so bool(l1) = True

Now, what I assume in the case of l3 = l1 and l2, l1 is evaluated as True so for short circuit evaluation, it returns l2.

In case of l4 = l1 or l2, again due to short circuit evaluation, l1 is returned since l1 is True.

So, you are getting the result like that. short circuit evaluation is nothing but--

  1. In the case of A and B, if A evaluates to True go on evaluating B and return the result of B. If A evaluates to False, then no point of evaluating B. Return the result of A.
False and print('hello')
>>> False
True and print('hello')
>>> hello
  1. In the case of A or B, if A evaluates to True, then there is no point in evaluating B. Just return the result of A. If A evaluates to False, then return the result of B.
True or (1/0)
>>> True
False or (1/0)
>>> ZeroDivisionError: division by zero

Note:

bool([]) = False
bool([1,2,'a']) = True
bool(['False']) = True


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...