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]))
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.
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.
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.
Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.
Include the in x
in the any()
:
urlsIwant = [x for x in allurls if any(w in x for w in words)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With