检測字符串之间的包括
本文地址: http://blog.csdn.net/caroline_wendy/article/details/27048955
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