Python3.4字符串包含 & 集合
来源:互联网 发布:盛势网络剧微博 编辑:程序博客网 时间:2024/04/28 06:33
"""字符串包含 & 集合"""#方法一:def containsAny(allstr,childstr):for c in allstr:if c in childstr: return Truereturn Falseallstr = "老毕很帅嘛"childstr = "帅"print(containsAny(allstr,childstr)) # True#方法二:def containsAny2(allstr,childstr):for item in filter(childstr.__contains__,allstr): #python3里直接使用filterreturn Truereturn Falseprint (containsAny2(allstr,childstr)) # True#方法三:#集合的intersection得到交集#bool(something),转成布尔型,除了为空返回False,其它只要有值都返回Truedef containsAny3(allstr,childstr):return bool(set(childstr).intersection(allstr))print (containsAny3(allstr,childstr)) # Trueprint (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']
运行结果:
bixiaopeng@bixiaopengtekiMacBook-Pro python_text$ python text_checkcontains.pyTrueTrueTrueFalse## 集合联合union:{'嘛', '老', '毕', '很', '帅'}## 集合差difference:{'老', '毕', '很', '嘛'}## 集合交集inetersection:{'帅'}## 返回集合中包含的所有属于一个集合且不属于另外一个的元素:{'老', '毕', '很', '嘛'}{'p', 'n', 'g', 'b', 'a', 'x', 'i', 'e', 'o'}['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']
微信公众帐号: wirelessqa
关于作者:
作者: 毕小朋 | 老 毕 邮箱: wirelessqa.me@gmail.com
微博: @WirelessQA 博客: http://blog.csdn.net/wirelessqa
1 0
- Python3.4字符串包含 & 集合
- Python3.4字符串包含 & 集合
- 断集合字符串是否包含某元素
- Python3.4字符串基础
- 输入一个字符串,求出该字符串包含的字符集合
- 检查字符串中是否包含某字符集合中的字符
- 面试:字符串集合 查找包含算法 的素数方案
- 字符串第一次包含目标字符集合元素的最小范围
- 集合中有包含关系的字符串去重
- JSTL判断一个list集合里是否包含某个字符串
- List集合针对元素中包含的字符串排序
- Python3学习(4)--集合list和tuple
- python3 字符串
- Python3字符串
- Python3 字符串
- python3字符串
- Python3 字符串
- 深入Python3 (Dive Into Python3)笔记4--字符串
- Android实战之小说阅读器,带有水平翻页,记录上次读取页码数
- 杭电2048神、上帝以及老天爷
- 传纸条(一)
- Speed Limit
- 怎样将IP地址转换为数字
- Python3.4字符串包含 & 集合
- 黑马程序员----交通灯管理系统
- 杭电 1276 士兵队列训练问题
- 设计模式之备忘录
- 关于蓝牙接收数据的解决方案
- jquery源码分析(2) jQuery对象的一些方法和属性 1
- 杭电2050折线分割平面
- Algorithm学习笔记 --- 百钱买百鸡问题(枚举练习)
- 点球大战 2539