Python list to XML and vice versa

后端 未结 2 924
长发绾君心
长发绾君心 2021-01-19 21:51

I have some python code that I wrote to convert a python list into an XML element. It\'s meant for interacting with LabVIEW, hence the weird XML array format. Anyways, here\

2条回答
  •  一整个雨季
    2021-01-19 22:47

    Try the following:

    from operator import mul
    
    def validate(array, sizes):
        if reduce(mul, sizes) != len(array):
            raise ValueError("Array dimension incompatible with desired sizes")
    
        return array, sizes
    
    def reshape(array, sizes):
        for s in sizes:
            array = [array[i:i + s] for i in range(0, len(array), s)]
    
        return array[0]
    
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    length = [2, 2, 3]
    
    print reshape(validate(data, length))
    
    length = [2, 2, 2]
    
    print reshape(validate(data, length))
    

    Output being:

    [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
    Traceback:
       (...)
    ValueError: Array dimension incompatible with desired sizes
    

    An alternative is using numpy arrays. Note that for this simple task, numpy is a rather big dependency, though you will find that most (common) array related tasks/problems already have an implementation there:

    from numpy import array
    
    print array(data).reshape(*length)  # optionally add .tolist() to convert to list
    

    EDIT: Added data validation

    EDIT: Example using numpy arrays (thanks to J.F.Sebastian for the hint)

提交回复
热议问题