Python3.4字符串包含 & 集合

  1. """ 
  2. 字符串包含 & 集合 
  3. """  
  4.   
  5. #方法一:  
  6. def containsAny(allstr,childstr):  
  7.     for c in allstr:  
  8.         if c in childstr: return True  
  9.     return False  
  10.   
  11. allstr = "老毕很帅嘛"  
  12. childstr = "帅"  
  13.   
  14. print(containsAny(allstr,childstr))  # True  
  15.   
  16. #方法二:  
  17. def containsAny2(allstr,childstr):  
  18.     for item in filter(childstr.__contains__,allstr): #python3里直接使用filter  
  19.         return True  
  20.     return False  
  21.   
  22. print (containsAny2(allstr,childstr)) # True  
  23.   
  24. #方法三:  
  25. #集合的intersection得到交集  
  26. #bool(something),转成布尔型,除了为空返回False,其它只要有值都返回True  
  27. def containsAny3(allstr,childstr):  
  28.     return bool(set(childstr).intersection(allstr))  
  29.   
  30. print (containsAny3(allstr,childstr)) # True  
  31.   
  32. print (containsAny3(allstr,"赞")) # False  
  33.   
  34.   
  35. #===========================集合拓展:===========================  
  36. print ("## 集合联合union: " )  
  37. print (set(childstr).union(set(allstr))) #{'嘛', '很', '毕', '老', '帅'}  
  38.   
  39. print ("## 集合差difference: ")  
  40. print (set(allstr).difference(set(childstr))) #{'嘛', '很', '毕', '老'}  
  41.   
  42. print("## 集合交集inetersection: ")  
  43. print (set(allstr).intersection(set(childstr))) #{'帅'}  
  44. print ("## 返回集合中包含的所有属于一个集合且不属于另外一个的元素: ")  
  45. print (set(allstr).symmetric_difference(set(childstr))) #{'老', '毕', '很', '嘛'}  
  46.   
  47. #集合的不重复性  
  48. test_str = "bixiaoxiaoxiaopengpeng"  
  49. #转换成集合  
  50. strset = set(test_str)  
  51. print(strset) #{'i', 'e', 'o', 'x', 'a', 'g', 'p', 'b', 'n'}  
  52.   
  53. #给集合排序  
  54. strlist = list(strset) #先将集合转成list  
  55.   
  56. #sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数  
  57. strlist.sort()  #sort没有返回值,但是会对列表的对象进行排序。  
  58. print(strlist)  # ->['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值