Python,itertool的ifilter

本文介绍了Python 2.7中itertools模块的ifilter方法使用方法及其应用场景,包括如何利用ifilter进行过滤操作,以及如何通过集合运算如交集、并集、差集等处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://docs.python.org/2.7/library/itertools.html

itertools中的ifilter方法,官方解释如下:

IteratorArgumentsResultsExample
ifilter()pred, seqelements of seq where pred(elem) is trueifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
其中第一个参数为pred,第二个参数为seq

返回一个迭代器,该迭代器中的元素是:seq中的元素在pred函数中返回true的元素的集合

该方法可以判断一个字符集合中是否包含另一个字符集合(不连续的)。

联想一下:

1、查找一个字符串中是否包含另一个字符串:str1.find(str2) 返回s2在s1中的起始位置,不存在返回-1

2、求两个list的交集(intersection)、并集(union)、差集(difference),用set来处理要比直接处理list要快

a = [1,2,3,4]
b = [1,2,3,3,'a']
c = set(a).difference(b)//差集 a-b
print c //set([4])
d = set(a).intersection(b)//交集
print d //set([1, 2, 3])
e = set(a).union(b)//并集
print e //set(['a', 1, ,2, 3, 4])
f = set(a).symmetric_difference(b) //new set with elements in either s or t but not both
print f //set(['a', 4])

3、判断一个字符或数字是否存在于列表中

a = [1,2,3,4, 'a']
b = 'a'
if(a.__contains__(b)):
    print 'exists'   //exists


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值