Recipe 1.8. Checking Whether a String Contains a Set of Characters(Python Cookbo
时间:2010-12-20 来源:Ray Z
1 >>> import itertools
2 >>> def containsAny(seq, aset):
3 for item in itertools.ifilter(aset.__contains__, seq):
4 return True
5 return False
6
7 >>> containsAny("abcd", "ae")
8 True
2 return not set(aset).difference(seq)
3
4 >>> containsAll("abc", "ad")
5 False
6 >>> containsAll("Abc", "Ac")
7 True
8 >>> L1 = [1, 2, 3, 3]
9 >>> L2 = [1, 2, 3, 4]
10 >>> set(L1).difference(L2)
11 set([])
12 >>> set(L2).difference(L1)
13 set([4])
2 >>> notrans = string.maketrans('', '')
3 >>> def containsAny(astr, strset):
4 return len(strset) != len(strset.translate(notrans, astr))
5
6 >>> def containsAll(astr, strset):
7 return not strset.translate(notrans, astr)
8
9 >>> "abc".translate(notrans, "ac")
10 'b'
11 >>> containsAny("abcde", "af")
12 True
13 >>> containsAll("abcef", "aef")
2 >>> def containsAny(seq, aset):
3 for item in itertools.ifilter(aset.__contains__, seq):
4 return True
5 return False
6
7 >>> containsAny("abcd", "ae")
8 True
difference 1 >>> def containsAll(seq, aset):
2 return not set(aset).difference(seq)
3
4 >>> containsAll("abc", "ad")
5 False
6 >>> containsAll("Abc", "Ac")
7 True
8 >>> L1 = [1, 2, 3, 3]
9 >>> L2 = [1, 2, 3, 4]
10 >>> set(L1).difference(L2)
11 set([])
12 >>> set(L2).difference(L1)
13 set([4])
code 1 >>> import string
2 >>> notrans = string.maketrans('', '')
3 >>> def containsAny(astr, strset):
4 return len(strset) != len(strset.translate(notrans, astr))
5
6 >>> def containsAll(astr, strset):
7 return not strset.translate(notrans, astr)
8
9 >>> "abc".translate(notrans, "ac")
10 'b'
11 >>> containsAny("abcde", "af")
12 True
13 >>> containsAll("abcef", "aef")
相关阅读 更多 +