Converting arrarys in Python to arrays in C

Anton Vredegoor anton at vredegoor.doge.nl
Wed Dec 17 13:08:54 EST 2003


Simon Foster <simon at uggs.demon.co.uk> wrote:

>I have some code which attempts to convert Python arrays (tuples of 
>tuples of tuples...) etc. into C arrays with equivalent contents.
>
>The prototype code is shown below.
>
>My only question is, is there some way of doing this without repeating 
>the try..except blocks ad-infinitum to handle 3D, 4D arrays etc.
>
>I can see there is a pattern here but I can't seem to turn it into a 
>loop.  Would a recursive solution do the trick?

Probably yes, but why reinvent the wheel? Numeric does what you want
already and allows for efficient conversions too [1].

Anton


[1] For example, using your code as a basis:

import Numeric

def test():
    cdata0 = 0
    
    cdata1 = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 )
    
    cdata2 = (( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ))
    
    for cdata in cdata0, cdata1, cdata2:
        a = Numeric.array(cdata)
        print a.shape
        print a
        print
    
if __name__=='__main__':
    test()






More information about the Python-list mailing list