- """
- 字符串包含 & 集合
- """
- #方法一:
- def containsAny(allstr,childstr):
- for c in allstr:
- if c in childstr: return True
- return False
- allstr = "老毕很帅嘛"
- childstr = "帅"
- print(containsAny(allstr,childstr)) # True
- #方法二:
- def containsAny2(allstr,childstr):
- for item in filter(childstr.__contains__,allstr): #python3里直接使用filter
- return True
- return False
- print (containsAny2(allstr,childstr)) # True
- #方法三:
- #集合的intersection得到交集
- #bool(something),转成布尔型,除了为空返回False,其它只要有值都返回True
- def containsAny3(allstr,childstr):
- return bool(set(childstr).intersection(allstr))
- print (containsAny3(allstr,childstr)) # True
- print (containsAny3(allstr,"赞")) # False
- #===========================集合拓展:===========================
- print ("## 集合联合union: " )
- print (set(childstr).union(set(allstr))) #{'嘛', '很', '毕', '老', '帅'}
- print ("## 集合差difference: ")
- print (set(allstr).difference(set(childstr))) #{'嘛', '很', '毕', '老'}
- print("## 集合交集inetersection: ")
- print (set(allstr).intersection(set(childstr))) #{'帅'}
- print ("## 返回集合中包含的所有属于一个集合且不属于另外一个的元素: ")
- print (set(allstr).symmetric_difference(set(childstr))) #{'老', '毕', '很', '嘛'}
- #集合的不重复性
- test_str = "bixiaoxiaoxiaopengpeng"
- #转换成集合
- strset = set(test_str)
- print(strset) #{'i', 'e', 'o', 'x', 'a', 'g', 'p', 'b', 'n'}
- #给集合排序
- strlist = list(strset) #先将集合转成list
- #sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数
- strlist.sort() #sort没有返回值,但是会对列表的对象进行排序。
- print(strlist) # ->['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']
Python3.4字符串包含 & 集合
最新推荐文章于 2024-03-11 15:00:17 发布