Python Cookbook学习记录 ch1_8_2013/10/23
2013-10-23 20:55
666 查看
1.8 检查字符串中是否包含某字符集合中的字符
a.最常用的方法,使用for循环,第一个序列式字符串,第二个集合
b.使用集合里面的取交集方法,如果能够取到交集,返回Ture,反之返回False
讨论:
书中后来提到了set的difference方法,difference方法在帮助文档的解释如下,即返回包含属于其中一个集合,但是不属于其他集合的元素的集合(=_=|||感觉我的语文表达水平很差)
书中还通过一个例子来解释:
书中还介绍了一种更复杂的方法,通过translate方法。translate的方法有两个参数,第一个参数是转换方案,第二个参数是需要删除的部分。如果两个字符串存在相同的部分 ,那么做完translate后肯定存在部分内容被删除,导致前后长度不一致,如果前后长度一致,则说明两个字符集合没有相同的部分。如果两个字符串完全相同,则长度为0,即全部都被删除了。
a.最常用的方法,使用for循环,第一个序列式字符串,第二个集合
Type "copyright", "credits" or "license()" for more information. >>> def containAny(seq,aset): for item in seq: if item in aset: return True return False >>> seq = 'abc' >>> import sets >>> aset1 = sets.Set('def') >>> aset2 = sets.Set('cdef') >>> containAny(seq,aset1) False >>> containAny(seq,aset2) True
b.使用集合里面的取交集方法,如果能够取到交集,返回Ture,反之返回False
>>> def containAny(seq,aset): return bool(set(seq).intersection(aset)) >>> containAny(aset1,aset2) True
讨论:
书中后来提到了set的difference方法,difference方法在帮助文档的解释如下,即返回包含属于其中一个集合,但是不属于其他集合的元素的集合(=_=|||感觉我的语文表达水平很差)
>>> help(set.difference) Help on method_descriptor: difference(...) Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.)
书中还通过一个例子来解释:
>>> L1 = [1,2,3,3] >>> L2 = [1,2,3,4] >>> set(L1).difference(L2) set([]) >>> set(L2).difference(L1) set([4])
书中还介绍了一种更复杂的方法,通过translate方法。translate的方法有两个参数,第一个参数是转换方案,第二个参数是需要删除的部分。如果两个字符串存在相同的部分 ,那么做完translate后肯定存在部分内容被删除,导致前后长度不一致,如果前后长度一致,则说明两个字符集合没有相同的部分。如果两个字符串完全相同,则长度为0,即全部都被删除了。
>>> import string >>> notrans = string.maketrans('','') #相当于没有对源字符串进行转换 >>> def containsAny(astr,strset): #如果前后长度不等表示有交集 return len(strset) != len(strset.translate(notrans,astr)) >>> def containsAll(astr,strset): #如果长度为0表示完全相同 return not strset.translate(notrans,astr) >>> str1 = 'hello world' >>> str2 = 'hello' >>> str3 = 'hello world' >>> containsAny(str1,str2) True >>> containsAll(str1,str2) True
相关文章推荐
- Python Cookbook学习记录 ch1_9_2013/10/23
- Python Cookbook学习记录 ch1_10_2013/10/23
- Python Cookbook学习记录 ch1_1_2013/10/20
- Python Cookbook学习记录 ch1_3_2013/10/21
- Python Cookbook学习记录 ch1_5_2013/10/22
- Python Cookbook学习记录 ch1_6_2013/10/22
- Python Cookbook学习记录 ch1_14_2013/10/25
- Python Cookbook学习记录 ch1_13_2013/10/24
- Python Cookbook学习记录 ch1_15_2013/10/25
- Python Cookbook学习记录 ch1_7_2013/10/22
- Python Cookbook学习记录 ch1_17_2013/10/25
- Python Cookbook学习记录 ch1_19_2013/10/27
- Python Cookbook学习记录 ch1_2_2013/10/21
- Python Cookbook学习记录 ch1_4_2013/10/22
- Python Cookbook学习记录 ch1_12_2013/10/24
- Python Cookbook学习记录 ch3_5/8_2013/10/30
- Python Cookbook学习记录 ch6_2_2013/11/7
- Python Cookbook学习记录 ch2_1_2013/10/27
- Python Cookbook学习记录 ch2_6/7/8_2013/10/27
- Python Cookbook学习记录 ch3_1/2_2013/10/29