熱線電話:13121318867

登錄
首頁精彩閱讀Python檢測字符串中是否包含某字符集合中的字符
Python檢測字符串中是否包含某字符集合中的字符
2017-12-23
收藏

Python檢測字符串中是否包含某字符集合中的字符

這篇文章主要介紹了Python檢測字符串中是否包含某字符集合中的字符,需要的朋友可以參考下

目的

檢測字符串中是否包含某字符集合中的字符

方法

最簡潔的方法如下,清晰,通用,快速,適用于任何序列和容器

代碼如下:
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])

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢