ucollections.rst 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. :mod:`ucollections` -- collection and container types
  2. =====================================================
  3. .. module:: ucollections
  4. :synopsis: collection and container types
  5. |see_cpython_module| :mod:`python:collections`.
  6. This module implements advanced collection and container types to
  7. hold/accumulate various objects.
  8. Classes
  9. -------
  10. .. function:: deque(iterable, maxlen[, flags])
  11. Deques (double-ended queues) are a list-like container that support O(1)
  12. appends and pops from either side of the deque. New deques are created
  13. using the following arguments:
  14. - *iterable* must be the empty tuple, and the new deque is created empty.
  15. - *maxlen* must be specified and the deque will be bounded to this
  16. maximum length. Once the deque is full, any new items added will
  17. discard items from the opposite end.
  18. - The optional *flags* can be 1 to check for overflow when adding items.
  19. As well as supporting `bool` and `len`, deque objects have the following
  20. methods:
  21. .. method:: deque.append(x)
  22. Add *x* to the right side of the deque.
  23. Raises IndexError if overflow checking is enabled and there is no more room left.
  24. .. method:: deque.popleft()
  25. Remove and return an item from the left side of the deque.
  26. Raises IndexError if no items are present.
  27. .. function:: namedtuple(name, fields)
  28. This is factory function to create a new namedtuple type with a specific
  29. name and set of fields. A namedtuple is a subclass of tuple which allows
  30. to access its fields not just by numeric index, but also with an attribute
  31. access syntax using symbolic field names. Fields is a sequence of strings
  32. specifying field names. For compatibility with CPython it can also be a
  33. a string with space-separated field named (but this is less efficient).
  34. Example of use::
  35. from ucollections import namedtuple
  36. MyTuple = namedtuple("MyTuple", ("id", "name"))
  37. t1 = MyTuple(1, "foo")
  38. t2 = MyTuple(2, "bar")
  39. print(t1.name)
  40. assert t2.name == t2[1]
  41. .. function:: OrderedDict(...)
  42. ``dict`` type subclass which remembers and preserves the order of keys
  43. added. When ordered dict is iterated over, keys/items are returned in
  44. the order they were added::
  45. from ucollections import OrderedDict
  46. # To make benefit of ordered keys, OrderedDict should be initialized
  47. # from sequence of (key, value) pairs.
  48. d = OrderedDict([("z", 1), ("a", 2)])
  49. # More items can be added as usual
  50. d["w"] = 5
  51. d["b"] = 3
  52. for k, v in d.items():
  53. print(k, v)
  54. Output::
  55. z 1
  56. a 2
  57. w 5
  58. b 3