现在的位置: 主页 > 新闻中心 > 文章正文

Python - 检测字符串之间的包含

作者:武警河南洛阳红丝带网 来源:www.027fck.com 未知发布时间:2017-09-09 10:25:36
Python - 检测字符串之间的包含 检测字符串之间的包含

Python中, 可以检测字符串之间的包含问题.

containsAny, 只要包含任何一个字符即可;

containsOnly, 所有字符都包含在内;

containsAll, 包含全部;

代码:

# -*- coding: utf-8 -*- ''' Created on 2014.5.25 @author: C.L.Wang ''' '''存在任何''' def containsAny(seq, aset): for c in seq: if c in aset: return True return False import itertools def containsAny2(seq, aset): for item in itertools.ifilter(aset.__contains__, seq) : return True return False def containsAny3(seq, aset): return bool(set(aset).intersection(seq)) '''全部存在''' def containsOnly(seq, aset): for c in seq: if c not in aset: return False return True '''包含全部''' def containsAll(seq, aset): #print(set(aset).difference(seq)) return not set(aset).difference(seq) import string notrans = string.maketrans('', '') def containsAny4(astr, strset): return len(strset) != len(strset.translate(notrans, astr)) def containsAll2(astr, strset): return not strset.translate(notrans, astr) if __name__ == '__main__': L1 = [1, 2, 3, 4] L2 = [5, 6, 7, 8] L3 = [1, 4, 7, 10] print(L1 constains any in L2 : + str(containsAny(L1, L2))) print(L1 constains any in L3 : + str(containsAny(L1, L3))) print(L1 constains any in L2 (2) : + str(containsAny2(L1, L2))) print(L1 constains any in L3 (2) : + str(containsAny2(L1, L3))) print(L1 constains any in L2 (3) : + str(containsAny3(L1, L2))) print(L1 constains any in L3 (3) : + str(containsAny3(L1, L3))) L4 = [1, 1, 2, 2, 3, 4] L5 = [1, 1, 2, 2, 3, 4, 5] print(L1 constains only in L4 : + str(containsOnly(L1, L4))) print(L1 constains only in L5 : + str(containsOnly(L1, L5))) print(L1 constains all in L4 (2) : + str(containsAll(L1, L4))) print(L1 constains all in L5 (2) : + str(containsAll(L1, L5))) pass
输出:

L1 constains any in L2 : False L1 constains any in L3 : True L1 constains any in L2 (2) : False L1 constains any in L3 (2) : True L1 constains any in L2 (3) : False L1 constains any in L3 (3) : True L1 constains only in L4 : True L1 constains only in L5 : True L1 constains all in L4 (2) : True L1 constains all in L5 (2) : False

http://www.2cto.com/

,可视化专题

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:恩施网站建设 http://enshi.45qun.com

上一篇:CF 196 Div 2 D (树形dp) 下一篇:最后一页