data.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # encoding: utf-8
  2. """Utilities for working with data structures like lists, dicts and tuples.
  3. """
  4. #-----------------------------------------------------------------------------
  5. # Copyright (C) 2008-2011 The IPython Development Team
  6. #
  7. # Distributed under the terms of the BSD License. The full license is in
  8. # the file COPYING, distributed as part of this software.
  9. #-----------------------------------------------------------------------------
  10. from .py3compat import xrange
  11. def uniq_stable(elems):
  12. """uniq_stable(elems) -> list
  13. Return from an iterable, a list of all the unique elements in the input,
  14. but maintaining the order in which they first appear.
  15. Note: All elements in the input must be hashable for this routine
  16. to work, as it internally uses a set for efficiency reasons.
  17. """
  18. seen = set()
  19. return [x for x in elems if x not in seen and not seen.add(x)]
  20. def flatten(seq):
  21. """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
  22. return [x for subseq in seq for x in subseq]
  23. def chop(seq, size):
  24. """Chop a sequence into chunks of the given size."""
  25. return [seq[i:i+size] for i in xrange(0,len(seq),size)]