经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C 语言 » 查看文章
python集合使用范例的代码
来源:cnblogs  作者:土豆师傅  时间:2018/12/13 9:31:34  对本文有异议

在代码过程中中,将代码过程中比较好的代码段珍藏起来,如下的代码是关于python集合使用范例的代码,希望能对大伙有用。

  1. # sets are unordered collections of unique hashable elements
  2. # Python23 tested vegaseat 09mar2005
  3. # Python v2.4 has sets built in
  4. import sets
  5. print "List the functions within module 'sets':"
  6. for funk in dir(sets):
  7. print funk
  8. # create an empty set
  9. set1 = set([])
  10. # now load the set
  11. for k in range(10):
  12. set1.add(k)
  13. print "nLoaded a set with 0 to 9:"
  14. print set1
  15. set1.add(7)
  16. print "Tried to add another 7, but it was already there:"
  17. print set1
  18. # make a list of fruits as you put them into a basket
  19. basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
  20. print "nThe original list of fruits:"
  21. print basket
  22. # create a set from the list, removes the duplicates
  23. fruits = sets.Set(basket)
  24. print "nThe set is unique, but the order has changed:"
  25. print fruits
  26. # let's get rid of some duplicate words
  27. str1 = "Senator Strom Thurmond dressed as as Tarzan"
  28. print "nOriginal string:"
  29. print str1
  30. print "A list of the words in the string:"
  31. wrdList1 = str1.split()
  32. print wrdList1
  33. # now create a set of unique words
  34. strSet = sets.Set(wrdList1)
  35. print "The set of the words in the string:"
  36. print strSet
  37. print "Convert set back to string (order has changed!):"
  38. print " ".join(strSet)
  39. print
  40. # comparing two sets, bear with me ...
  41. colorSet1 = sets.Set(['red','green','blue','black','orange','white'])
  42. colorSet2 = sets.Set(['black','maroon','grey','blue'])
  43. print "colorSet1 =", colorSet1
  44. print "colorSet2 =", colorSet2
  45. # same as (colorSet1 - colorSet2)
  46. colorSet3 = colorSet1.difference(colorSet2)
  47. print "nThese are the colors in colorSet1 that are not in colorSet2:"
  48. print colorSet3
  49. # same as (colorSet1 | colorSet2)
  50. colorSet4 = colorSet1.union(colorSet2)
  51. print "nThese are the colors appearing in both sets:"
  52. print colorSet4
  53. # same as (colorSet1 ^ colorSet2)
  54. colorSet5 = colorSet1.symmetric_difference(colorSet2)
  55. print "nThese are the colors in colorSet1 or in colorSet2, but not both:"
  56. print colorSet5
  57. # same as (colorSet1 & colorSet2)
  58. colorSet6 = colorSet1.intersection(colorSet2)
  59. print "nThese are the colors common to colorSet1 and colorSet2:"
  60. print colorSet6

  





 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号