replace deepest level of nested list

George Sakkis george.sakkis at gmail.com
Mon Sep 4 11:14:46 EDT 2006


David Isaac wrote:

> I have a list of lists, N+1 deep.
> Like this (for N=2):
> [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11'
> ,'b11']]]
>
> I want to efficiently produce the same structure
> except that the utlimate lists are replaced by a chosen (by index) item.
> E.g.,
> [['r00','r01'],['r10','r11']]
>
> N is not known ahead of time.
>
> Suggestions?
>
> Thanks,
> Alan Isaac

Numeric/Numpy is ideal for this:



from Numeric import array



def slicelist(nestedlist,index):

    a = array(nestedlist,'O')

    # return the slice a[:,:,...,:,index]

    fullindex = [slice(None)] * len(a.shape)

    fullindex[-1] = index

    return a[fullindex].tolist()


George




More information about the Python-list mailing list