Saturday 9 February 2019
if 'a' or 'b' in L, where L is a list (Python)
Answer
Answer
I am having trouble with the following logic:
Lets say I have a list L = ['a', 'b', 'c']
Both items are in the list...
if ('a' or 'b') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints It's there!
Only the first item is in the list...
if ('a' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints It's there!
Neither item in the list...
if ('e' or 'd') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints No sorry
Here's the confusing one Only the second item in the list...
if ('e' or 'a') in L:
print 'it\'s there!'
else:
print 'No sorry'
prints No sorry
I do not understand why this is not registering as a true statement. How does this generalize to an or statement with n conditionals?
Forehead-slapping easy answer in 3,2,1...
Answer
Let's break down the expression:
('e' or 'a')
will first check if 'e'
is True. If it is, the expression will return 'e'
. If not, it will return 'a'
.
Since all non-empty strings returns True
, this expression will always return 'e'
. This means that if ('e' or 'a') in L:
can be translated to if 'e' in L
, which in this case is False
.
A more generic way to check if a list contains at least one value of a set of values, is to use the any
function coupled with a generator expression.
if any(c in L for c in ('a', 'e')):
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment