Advertisement
tari

tari

Jan 5th, 2011
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. def nested_append(nlist, element, depth):
  2.     """Appends element to nlist at depth levels in, where levels are delimited
  3.       by sublists and begin at 1 for the list root.  Levels prior to depth
  4.       will be created if they do not exist, and depths less than 1 are
  5.       treated as if they were 1.
  6.      
  7.       Example:
  8.       >>> a = []
  9.       >>> nested_append(a, '1.0', 1)
  10.       # a = ['1.0']
  11.       >>> nested_append(a, '2.0', 2)
  12.       # a = ['1.0', ['2.0']]
  13.       >>> nested_append(a, ['3.0','3.1'], 2)
  14.       # a = ['1.0', ['2.0', ['3.0', '3.1']]]
  15.       >>> nested_append(a, '1.1', 1)
  16.       # a = ['1.0', ['2.0', ['3.0', '3.1']], '1.1']
  17.      
  18.       Note that the second call for level 2 is equivalent to two calls to
  19.       nested_append at level 3 with elements '3.0' and '3.1'.
  20.    if depth <= 1:
  21.        # Have hit the target level
  22.        nlist.append(element)
  23.    else:
  24.        if not isinstance(nlist[-1], list):
  25.            # Next level doesn't exist yet, so create it
  26.            nlist.append([])
  27.        nested_append(nlist[-1], element, depth - 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement