Python で Beautiful Soup を使用して、HTML ファイルからデータをスクレイピングしています。場合によっては、Beautiful Soup はstringとNoneTypeオブジェクトの両方を含むリストを返します。NoneTypeすべてのオブジェクトを除外したいと思います。
Python では、NoneTypeオブジェクトを含むリストは反復可能ではないため、リスト内包表記はこのオプションではありません。具体的には、lisを含むリストがあり、 のNoneTypesようなことをしようとすると[x for x in lis (some condition/function)]、Python はエラー をスローしますTypeError: argument of type 'NoneType' is not iterable。
他の投稿で見たように、この機能をユーザー定義関数に実装するのは簡単です。これが私の味です:
def filterNoneType(lis):
lis2 = []
for l in links: #filter out NoneType
if type(l) == str:
lis2.append(l)
return lis2
However, I'd love to use a built-in Python function for this if it exists. I always like to simplify my code when possible. Does Python have a built-in function that can remove NoneType objects from lists?