Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python any() function within a list comprehension

I'm new to Python (2 weeks!) and struggling with the following:

I have a list of URLs that I want to iterate through and find just certain URLs. To do this I want to test any members of a tuple are present in the URL.

I've figured out I need a any() statement but can't get the syntax right:

allurls = [<big list of URLs>]

words = ('bob', 'fred', 'tom')

urlsIwant = [x for x in allurls if any(w for w in words) in x]

gets me

TypeError: 'in <string>' requires string as left operand, not bool

I don't think it's relevant but my actual code is

urlsIwant = sorted(set([x for x in allurls if dict['value'] in x and any(w for w in words) in x]))
like image 365
reaco Avatar asked May 20 '14 08:05

reaco


People also ask

What does any () do in Python?

Python any() Function The any() function returns True if any item in an iterable are true, otherwise it returns False. If the iterable object is empty, the any() function will return False.

How do you call a function in list comprehension?

Answer: You can use any expression inside the list comprehension, including functions and methods. An expression can be an integer 42 , a numerical computation 2+2 (=4) , or even a function call np. sum(x) on any iterable x . Any function without return value, returns None per default.

What is the function of any () and all () in Python?

The Python any() and all() functions evaluate the items in a list to see which are true. The any() method returns true if any of the list items are true, and the all() function returns true if all the list items are true.

Can you call a function inside a list?

Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.


1 Answers

Include the in x in the any():

urlsIwant = [x for x in allurls if any(w in x for w in words)]
like image 194
sshashank124 Avatar answered Oct 11 '22 11:10

sshashank124