目的
檢測字符串中是否包含某字符集合中的字符
方法
最簡潔的方法如下,清晰,通用,快速,適用于任何序列和容器
def containAny(seq,aset):
??? for c in seq:
???????? if c in aset:
??????????????? return True
??? return False
????? 第二種適用itertools模塊來可以提高一點性能,本質上與前者是同種方法(不過此方法違背了Python的核心觀點:簡潔,清晰)
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
?import itertools
def? containAny(seq,aset):
???? for item in itertools.ifilter(aset.__contain__,seq):
??????????? return True
???? return False
?
如果要檢測兩個字符串是否為包含關系,此時必須檢查所有子項,最好適用set類型,其中set(aset).difference(seq)是指存在于aset中而seq沒有的元素:
def? containAll(seq,aset):
????? return not set(aset).difference(seq)
例如下面這個例子:
In [4]: L1=[1,2,3,4]
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是指兩個集合獨有的元素
In [9]: L2=[3,2,4,5]
In [10]: x=set(L1)
In [11]: x.symmetric_difference(L2)
Out[11]: set([1, 5])
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
