I'm looking for an oneliner for this below logic:
links (list) variable will contain = ['**www.google.com/api/1.js**','**/path.js**']
url = "mysite.com"
valid_links = [url + u for u in links if not urlparse(u).netloc ]
This will give me only ['mysite.com/path.js'] but not 'www.google.com' in the list. I need full urls as it is and paths appended with my own url.
So i added else block:
url = "mysite.com"
valid_links = [url + u for u in links if not urlparse(u).netloc else u]
Can someone help me to get rid of the syntax error for this oneliner.
I tried it with
for #[iter]
if:
....
append to list
else:
....
append to list
But i want understand how to convert it in a oneliner
I'm looking for an oneliner.
Here is it:
and if you want to implement if/else the right syntax would be:
both variants printing in case of the given list:
Notice that:
The provided if/else expression works anywhere. I use it often in assignments like for example:
x = 2 if y==3 else 1It sets x to 2 if the variable y has the value 3 and if not it sets x to 1.
The
ifin the list comprehension is an item selection filter and anelsedoes not make any sense there.In other words the if/else expression has nothing to do with the list comprehension as such. You don't want to skip any items from the list (this is the purpose of a final
ifor multipleifs in list comprehension). You want the resulting item value to be another one depending on a condition.See Ternary conditional operator in Python (Wikipedia)