I have a list of URLs in first_list. Now I want to get only those URLs which is meet argument_lst condition.
In argument_lst, I have provided some specific domain names. I only need those URLs from the first_list If they match with argument_lst.
Here is my code:
first_list = ['https://www.abc45f.com/r/comments/dummy_url/', 'https://dfc.com/test_test/', 'https://www.kls.com/fsdnfklns_dfdsj','https://example11.com/app/1642038659010248255/']
argument_lst = ['abc45f.com', 'example11.com',5,7,8]
bl_lst = []
for lst in first_list:
all_element = lst
bl_lst.append(all_element)
for l in argument_lst:
if l in bl_lst:
print(l)
I want to achieve something like this:
https://www.abc45f.com/r/comments/dummy_url/
https://example11.com/app/1642038659010248255/
Could anyone please help me?
Thanks
CodePudding user response:
You can achieve it with an exception handling block,
first_list = ['https://www.abc45f.com/r/comments/dummy_url/', 'https://dfc.com/test_test/', 'https://www.kls.com/fsdnfklns_dfdsj','https://example11.com/app/1642038659010248255/']
argument_lst = ['abc45f.com', 'example11.com', 5, 7, 8]
output_list = []
for arg in argument_lst:
for el in first_list:
try:
if arg in el:
output_list.append(el)
except TypeError:
continue
print(output_list)
The try-catch
block will attempt to find if an element from the argument_list
is in any of the elements of the first_list
. If it is, then the code appends that member of the first_list
to the output_list
. If it is not, it just skips it.
However, if the argument is not a string (an integer in your case) the code will raise a TypeError
exception because you will be trying to compare an integer and a string. In that case, the try-catch
block will handle the exception, and bypass it - the continue
statement will simply move on to the next argument. This will only happen if the exception is of the TypeError
type, anything else will still cause the code to crash. It's important to narrow down the exceptions the code is handling as much as possible, to allow it to crash on things that are actually unexpected.