目的
檢測字符串中是否包含某字符集合中的字符
方法
最簡潔的方法如下,清晰,通用,快速,適用于任何序列和容器
itertools.ifilter(predicate, iterable)的說明
Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true.
例如:
ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
def containAny(seq,aset):
for item in itertools.ifilter(aset.__contain__,seq):
return True
return False
如果要檢測兩個字符串是否為包含關(guān)系,此時必須檢查所有子項,最好適用set類型,其中set(aset).difference(seq)是指存在于aset中而seq沒有的元素:
例如下面這個例子:
In [5]: L2=[1,4,3,1]
In [6]: containAll(L1,L2)
Out[6]: True
In [7]: containAll(L2,L1)
Out[7]: False
注意一下,set.symmetric_difference是指兩個集合獨有的元素
新聞熱點
疑難解答
圖片精選