Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def nested_append(nlist, element, depth):
- """Appends element to nlist at depth levels in, where levels are delimited
- by sublists and begin at 1 for the list root. Levels prior to depth
- will be created if they do not exist, and depths less than 1 are
- treated as if they were 1.
- Example:
- >>> a = []
- >>> nested_append(a, '1.0', 1)
- # a = ['1.0']
- >>> nested_append(a, '2.0', 2)
- # a = ['1.0', ['2.0']]
- >>> nested_append(a, ['3.0','3.1'], 2)
- # a = ['1.0', ['2.0', ['3.0', '3.1']]]
- >>> nested_append(a, '1.1', 1)
- # a = ['1.0', ['2.0', ['3.0', '3.1']], '1.1']
- Note that the second call for level 2 is equivalent to two calls to
- nested_append at level 3 with elements '3.0' and '3.1'.
- if depth <= 1:
- # Have hit the target level
- nlist.append(element)
- else:
- if not isinstance(nlist[-1], list):
- # Next level doesn't exist yet, so create it
- nlist.append([])
- nested_append(nlist[-1], element, depth - 1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement