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

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值