[Python] python集合使用范例 →→→→→进入此内容的聊天室

来自 , 2020-02-20, 写在 Python, 查看 133 次.
URL http://www.code666.cn/view/38220e6a
  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
  61. #//python/5736

回复 "python集合使用范例"

这儿你可以回复上面这条便签

captcha