Python,itertool的ifilter

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


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值