How to remove only zero digit from python list?

前端 未结 4 1667
春和景丽
春和景丽 2021-01-19 18:25

I want to remove 0 only from my list:

>>> mylist = [0, 1, None, 2, False, 1, 0]
<
4条回答
  •  萌比男神i
    2021-01-19 18:39

    The x is not 0 approach works, but is probably not optimal. There speed enhancements by using a list comprehension instead of using calls to list() and to filter().

    Running this in a Jupyter notebook and taking advantage of the builtin %timeit magic to see how quickly each of these can return the result.

    mylist = [0, 1, None, 2, False, 1, 0]
    

    Using list() and filter()

    %timeit list(filter(lambda x: x is not 0, mylist))
    **1.12 µs** ± 17.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    Using a list comprehsion

    %timeit [i for i in mylist if i is not 0]
    **411 ns** ± 8.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    We see that the list comprehension technique is significantly faster.

提交回复
热议问题