Native Python function to remove NoneType elements from list?

后端 未结 5 1780
终归单人心
终归单人心 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:54

    You can do this using list comprehension:

    clean = [x for x in lis if x != None]
    

    As pointed in the comments you could also use is not, even if it essentially compiles to the same bytecode:

    clean = [x for x in lis if x is not None]
    

    You could also used filter (note: this will also filter empty strings, if you want more control over what you filter you can pass a function instead of None):

    clean = filter(None, lis)
    

    There is always the itertools approach if you want more efficient looping, but these basic approaches should work for most day to day cases.

提交回复
热议问题