Native Python function to remove NoneType elements from list?

后端 未结 5 1811
终归单人心
终归单人心 2020-12-30 20:42

I\'m using Beautiful Soup in Python to scrape some data from HTML files. In some cases, Beautiful Soup returns lists that contain both string and NoneType

5条回答
  •  [愿得一人]
    2020-12-30 20:58

    List comprehension, as other answers proposed or, for the sake of completeness:

    clean = filter(lambda x: x is not None, lis)
    

    If the list is huge, an iterator approach is superior:

    from itertools import ifilter
    clean = ifilter(lambda x: x is not None, lis)
    

提交回复
热议问题