当前位置:Gxlcms > Python > Python内置函数——set&frozenset

Python内置函数——set&frozenset

时间:2021-07-01 10:21:17 帮助过:22人阅读

Python内置函数——set&frozenset


set
  1. set()
  2. set对象实例化
  3. >>> set('add')
  4. set(['a', 'd'])
  5. >>> set('python').add('hello')
  6. >>> print set('python').add('hello')
  7. None
  8. >>> a = set('python')
  9. >>> a
  10. set(['h', 'o', 'n', 'p', 't', 'y'])
  11. >>> a.add('hello')
  12. >>> a
  13. set(['h', 'o', 'n', 'p', 't', 'y', 'hello'])
  14. >>> a.update('python')
  15. >>> a
  16. set(['h', 'o', 'n', 'p', 't', 'y', 'hello'])
  17. >>> a.update('hello')
  18. >>> a
  19. set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y', 'hello'])
  20. >>> a.remove('hello')
  21. >>> a
  22. set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])
  23. >>> b = set('hello')
  24. >>> b
  25. set(['h', 'e', 'l', 'o'])
  26. >>> a - b
  27. set(['y', 'p', 't', 'n'])
  28. >>> a & b
  29. set(['h', 'e', 'l', 'o'])
  30. >>> a | b
  31. set(['e', 'h', 'l', 'o', 'n', 'p', 't', 'y'])
  32. >>> a != b
  33. True
  34. >>> a == b
  35. False
  36. >>> b in a
  37. False
  38. >>> a in b
  39. False
  40. >>> c = set('hell')
  41. >>> c in b
  42. False
  43. >>> b
  44. set(['h', 'e', 'l', 'o'])
  45. >>> c
  46. set(['h', 'e', 'l'])
  47. >>> 'h' in c
  48. True
  49. >>> 'p' in c
  50. False

frozenset

  1. frozenset([iterable])
  2. 产生一个不可变的set
  3. >>> a = frozenset(range(10))
  4. >>> a
  5. frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  6. >>> a.remove(0)
  7. Traceback (most recent call last):
  8. File "<pyshell#189>", line 1, in <module>
  9. a.remove(0)
  10. AttributeError: 'frozenset' object has no attribute 'remove'
  11. >>> b = set(range(10))
  12. >>> b
  13. set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  14. >>> b.remove(1)
  15. >>> b
  16. set([0, 2, 3, 4, 5, 6, 7, 8, 9])

以上就是Python内置函数——set&frozenset的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行