python使用filter去除list中的空元素和补充filterfalse的用法

    xiaoxiao2025-04-25  12

    1

    filter() 之前在某题中用到过一次,但确实很少用,还是记下来为好。

    #把空string删了 res = ['One Hundred Eleven', 'Billion', 'Twenty Two', 'Million', '', 'One Hundred'] ' '.join(list(filter(None, res))) #output: 'One Hundred Eleven Billion Twenty Two Million One Hundred'

    filter(function, iterable) 相当于: (item for item in iterable if function(item)) if function is not None 和 (item for item in iterable if item) if function is None

    2

    filterfalse()

    就是留下bool是False的元素: 内部相当于:

    def filterfalse(predicate, iterable): # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 if predicate is None: predicate = bool for x in iterable: if not predicate(x): yield x

    区别:

    In [292]: list(filter(lambda x: x%2, range(10))) Out[292]: [1, 3, 5, 7, 9] In [293]: list(itertools.filterfalse(lambda x: x%2, range(10))) Out[293]: [0, 2, 4, 6, 8]
    最新回复(0)