I am using list comprehension to gather facebook links from a list of urls.
Here is the list:
list1 = ['facebook.com','johnsmithfacebook.com','amazon.com','google.com','stackoverflow.com']
Now I'll do list comprehension to grab the facebook urls, returning np.nan
if nothing is found:
facebook = [i for i in list1 if 'facebook' in i] or pd.np.nan
And I'll join the strings if a result exists:
if facebook:
facebook = ', '.join(facebook)
print(facebook)
'facebook.com, johnsmithfacebook.com'
Great. That works.
But if it there are no facebook urls, and np.nan
is returned instead, I run into a problem:
# list
list2 = ['amazon','google']
facebook = [i for i in list2 if 'facebook' in i] or np.nan
if facebook: # nan check
facebook = ', '.join(facebook) # join if not nan
TypeError Traceback (most recent call last)
<ipython-input-52-1856f748f805> in <module>
1 if facebook:
----> 2 facebook = ', '.join(facebook)
TypeError: can only join an iterable
The facebook variable is nan
, so how did it get past the if facebook:
check?
print(facebook)
nan
The error can only join an iterable
sounds like I'm trying to join None
or Nan
from what I've read on google, but I tried to make sure nans
didn't get past this point.
The or np.nan
isn't needed at all, an empty array isn't truthy so it won't enter the if statement.
facebook = [i for i in list2 if 'facebook' in i]
On top of that, you don't even need the if statement since you'll just get an empty string if you try to join an empty list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.