Python檢測字符串中是否包含某字符集合中的字符
目的
檢測字符串中是否包含某字符集合中的字符
方法
最簡潔的方法如下,清晰,通用,快速,適用于任何序列和容器
def containAny(seq,aset):
for c in seq:
if c in aset:
return True
return False
第二種適用itertools模塊來可以提高一點性能,本質(zhì)上與前者是同種方法(不過此方法違背了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])
相關文章
LyScript實現(xiàn)對內(nèi)存堆棧掃描的方法詳解
LyScript插件中提供了三種基本的堆棧操作方法,其中push_stack用于入棧,pop_stack用于出棧,peek_stac可用于檢查指定堆棧位置處的內(nèi)存參數(shù)。所以本文將利用這一特性實現(xiàn)對內(nèi)存堆棧掃描,感興趣的可以了解一下2022-08-08Python實例方法與類方法和靜態(tài)方法介紹與區(qū)別分析
在 Python 中,實例方法(instance method),類方法(class method)與靜態(tài)方法(static method)經(jīng)常容易混淆。本文通過代碼例子來說明它們的區(qū)別2022-10-10python中24小時制轉(zhuǎn)換為12小時制的方法
最近需要實現(xiàn)一個需求,求用戶輸入24小時制的時間,然后顯示12小時制的時間。具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06Python轉(zhuǎn)換HTML到Text純文本的方法
這篇文章主要介紹了Python轉(zhuǎn)換HTML到Text純文本的方法,分析了常用的兩種方法,非常具有實用價值,需要的朋友可以參考下2015-01-01