سؤال

sample code

list = [i.get('content').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"})]

The problem is that .encode('utf-8') will raise an error:

AttributeError: 'NoneType' object has no attribute 'encode'

if one of the elements of the list is None.

I am wondering if there is a 'pythonic' way of keeping it in one line and ignoring None elements. For example can you put a if not None clause in the list? Thanks.

هل كانت مفيدة؟

المحلول

I would break this up into a generator expression for the initial fetching to limit the lookup, so get is only called once for performance.

items_i = (i.get('content') for i in self.soup.find_all('meta',attrs={"name": "description"}))
items = [i.encode('utf-8') for i in items_i if i]

نصائح أخرى

you can give .get a default argument to use instead of None

[i.get('content','').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"})]

or you can filter it out

[i.get('content').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"}) if i.get('content') is not None]

you should note that its not i that is none but rather its 'content'

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top