replace deepest level of nested list
Roberto.Bonvallet at cern.ch
Mon Sep 4 16:54:27 CEST 2006
David Isaac wrote:
> I have a list of lists, N+1 deep.
> Like this (for N=2):
> I want to efficiently produce the same structure
> except that the utlimate lists are replaced by a chosen (by index) item.
> N is not known ahead of time.
First thing I came up with:
>>> l = [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11','b11']]]
>>> def get_deepest(l, n):
... if isinstance(l, list):
... return [get_deepest(s, n) for s in l]
... return l[n]
>>> get_deepest(l, 0)
[['r00', 'r01'], ['r10', 'r11']]
>>> get_deepest(l, 1)
[['g00', 'g01'], ['g10', 'g11']]
n is the chosen index.
More information about the Python-list