Python,itertool的ifilter

来源:互联网 发布:怎么找网络水军 编辑:程序博客网 时间:2024/05/01 09:16

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

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

IteratorArgumentsResultsExampleifilter()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-bprint 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 bothprint f //set(['a', 4])

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

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


0 0
原创粉丝点击