Native Python function to remove NoneType elements from list?

后端 未结 5 1828
终归单人心
终归单人心 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 21:03

    For those who came here from Google

    In Python3 you can implement this using .__ne__ dunder method (or 'magic method' if you will):

    >>> list1 = [0, 'foo', '', 512, None, 0, 'bar']
    >>> list(filter(None.__ne__, list1))
    [0, 'foo', '', 512, 0, 'bar']
    

    This is how it works:

    • None.__ne__(None) --> False

    • None.__ne__(anything) --> NotImplemented

    NotImplemented exeption effectively is True, e.g.:

    >>> bool(None.__ne__('Something'))
    True
    

    As of the beginning of 2019, Python has no built-in function for filtering None values which avoids common pitfals with deleting zeroes, empty strings, etc.

提交回复
热议问题