What is a better way to deal with unknown list structures in python?
Question: My python program receives MIDI data from a C library. Sometimes the data will
look like this:

    
    
    [[[[240,0,1,116]]],[[[3,100,8,1]]],[[[107,247,0,0]]]]
    

and sometimes it will include timestamps like this:

    
    
    [[[[240,0,1,116],26738]],[[[3,100,8,1],26738]],[[[107,247,0,0],26738]]]
    

I need the data in an array of bytes, with the timestamp values discarded. The
code I wrote to do this is:

    
    
            def convertMidiSysex(data):    
                while isinstance(data[0][0], list):
                    out = []
                    for index, value in enumerate(data):
                        out = out+value
                    data = out
    
                out = array.array('B')
                for i in range(len(data)):
                    if isinstance(data[i], list):
                        for j in range(len(data[i])):
                            out.append(data[i][j])
                            if out[-1] == 247:  # 0xF7 is marker to end sysex message
                                return out
    

I can't help feeling that I'm doing this the hard way. Is there a better
approach to this?


Answer: Assuming the depth is always consistent:

    
    
    from itertools import takewhile
    
    def convertMidiSysex(data):
        values = takewhile(lambda v: v != 247,
                           (a for x in data for a in x[0][0]))
        out = array.array('B', values)
        out.append(247)
        return out
    

Examples:

    
    
    >>> convertMidiSysex([[[[240,0,1,116]]],[[[3,100,8,1]]],[[[107,247,0,0]]]])
    array('B', [240, 0, 1, 116, 3, 100, 8, 1, 107, 247])
    >>> convertMidiSysex([[[[240,0,1,116],26738]],[[[3,100,8,1],26738]],[[[107,247,0,0],26738]]])
    array('B', [240, 0, 1, 116, 3, 100, 8, 1, 107, 247])
    

