Testing multiple string in conditions in list comprehension [duplicate]

2024/11/19 1:28:01

I am trying to add multiple 'or' clauses to a python if statement using list comprehension. My code is shown below. I would like to keep the list comprehension. In terms of pseudocode, the logic would simply be:

Alive_Beatles = each name that contains '(Beatle)' and either ('Paul', 'Yoko' or 'Ringo')

The code only returns Paul and skips Ringo and Yoko.

Names = ["John Lennon (Beatle)",  "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"]
Alive_Beatles = [n for n in Names if ("Beatle" and ("Paul" or "Ringo" or "Yoko")) in n]print Alive_Beatles
Answer

You need to test each name explicitly if it's in n:

[n for n in Names if ("Beatle" in n and ("Paul" in n or "Ringo" in n or "Yoko" in n))]

Otherwise the and and or use the truth value of you search strings (and each non-empty string is always True) and finally tests if Paul in n (the first truth value of the ors).

The documentation explicitly mentions this:

4.2. Boolean Operations — and, or, not

These are the Boolean operations, ordered by ascending priority:

Operation     Result                                Notes
x or y        if x is false, then y, else x         (1)
x and y       if x is false, then x, else y         (2)
not x         if x is false, then True, else False  (3)

Notes:

(1) This is a short-circuit operator, so it only evaluates the second argument if the first one is false.

(2) This is a short-circuit operator, so it only evaluates the second argument if the first one is true.

(3) not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

So "Beatle" and (...) evaluates according to (2) to the second argument because "Beatle" is truthy and according to (1) it evaluates to the first argument of the chained ors: "Paul" because it's also truthy.

https://en.xdnf.cn/q/118604.html

Related Q&A

Filter range from two dates in the same query Django/Python

I need the result from a query that filters two dates from the same model. I need to get in the result 5 days (today plus 4 days) from original date and sale from target date (today plus 4 more days) b…

Python While/For loop

how can I make this into a while loop and output the same thing????for x in range(56,120) :if (x < 57) :summation = 0summation = x + summationif (x == 119) :print (“Sum of integers from 56 to 1…

Read a file into a nested dictionary?

Say I have a simple file like so holding arbitrary values:A, 20, Monday, 14, Tuesday, 15, Tuesday, 16 B, 40, Wednesday, 14, Friday, 12How would I get it into a nested dictionary so that each k/v pair l…

Using .replace function

I have a code with more than 2500 lines that contains several references to GIS layers. I need to replace these layers in the code for several web maps so I have to find a way to automate a find and re…

Python Turtle unit of measurement

When we instantiate a turtle object, we can draw a circle. I wonder about the radius parameter of the circle() method. import turtle myTurtle = turtle.Turtle() myTurtle.circle(50)What is the unit of me…

Python reverse() vs [::-1] slice performance [duplicate]

This question already has answers here:Difference between reverse and [::-1](2 answers)Time complexity of reversed() in Python 3(1 answer)Closed last year.Python provides two ways to reverse a list: Li…

Django Callback on Facebook Credits

I would like to use Facebook Credits with my Django Application.In the Facebook Credits documentation, there is only a sample for the callback page in PHP (https://developers.facebook.com/blog/post/489…

Remove \n from each string stored in a python list

I have a python list in which look like this:my_list = [OFAC\n, Social Media Analytics\n, Teaching Skills\n, Territory...\n, Active Directory...\n, Business Research\n, Call Center...\n, Treatment of d…

Optimizing loop. Faster ResultList.append( [ c, d, c[1]/d[1]] )? Array? Map?

The following works well but Id like to make it faster. The actual application could process Tuple1 and Tuple2 each with 30,000 elements and 17 nested sequences per element. I see numerous questions …

Why do I get an error name play is not defined when I think it is?

Full error: line 10, in <module>colour = play() NameError: name play is not definedI cant seem to find a reason for this issue anywhere on here. I am trying to assign the returned string to the v…