如何在python2.7中创建静态类型的n维数组?

2024-05-12 17:11:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个python模块,它允许人们为labview测试系统的自动化编写python脚本。其思想是,该模块将有一些方法允许用户从labview获取测试输入参数,用python进行一些计算,将参数发送回labview并运行测试。你知道吗

Labview使用静态类型的数据,尤其是在数组中。如果将不同类型的数据写入labview数组,则labview会将其强制为数组的静态类型(例如,不能将浮点值写入int32数组)

当python从python获取数据时(使用labview的“flatte to xml”),数据将与维度大小列表一起传输(每个维度对应一个大小及其数据类型)。必须以相同的数据类型返回数据。我想创建这些数据类型的数据结构(字典、列表、元组)。但是,在Python2.7中,如果数组是一个列表(或者多维数组中是一个列表列表),动态数据类型将允许某人,比如说,将两个整数除以,并将一个浮点值写入数组中,该数组应静态类型化为整数。你知道吗

是否有以下方法:1)如果用户的脚本试图写入错误的数据类型,则引发异常?或者2)让程序自动将值转换为数据类型?我想我更愿意提出一个例外。你知道吗

我想知道是否有一些有效的和通用的方法来创建静态类型的多维数组,它要么引发异常,要么将数据强制为所需的类型。你知道吗

我正在努力解决的另一个问题是如何动态创建n维数组。我在看列表理解,但大多数的例子,文档和答案只涉及2或3个维度和已知的大小。在本例中,我将有一个维度大小列表,其中包含未知数量的维度。你知道吗

作为Labview的示例,以下是二维数组在xml中的外观:

<Array>
 <Name>My2DArray</Name>
 <Dimsize>2</Dimsize>
 <Dimsize>2</Dimsize>
 <I32>
  <Name>Numeric</Name>
  <Val>-1</Val>
 </I32>
 <I32>
  <Name>Numeric</Name>
  <Val>1</Val>
 </I32>
 <I32>
  <Name>Numeric</Name>
  <Val>0</Val>
 </I32>
 <I32>
  <Name>Numeric</Name>
  <Val>3</Val>
 </I32>
</Array>

这是我尝试过的,它似乎工作正常,但可能不是最好的方法。如果“node”是上述XML的etree文档:

import numpy as np
def XMLType_to_dType(XMLType):
    switch = {
        'Boolean' : np.dtype('b'),
        'String'  : np.dtype('S'),
        'i8' : np.dtype('i1'),      
        'I16': np.dtype('i2'),
        'I32': np.dtype('i4'), 
        'I64': np.dtype('i8'),
        'U8' : np.dtype('u1'),
        'U16': np.dtype('u2'),
        'U32': np.dtype('u4'),
        'U64': np.dtype('u8'),
        'SGL': np.dtype('f2'),
        'DBL': np.dtype('f4'),
        'EXT': np.dtype('f8'),
        'CSG': np.dtype('c2'),
        'CDB': np.dtype('c4'),
        'CXT': np.dtype('c8'),
    } 
    dType =switch.get(XMLType)
    assert (dType != None),'Error in XML_to_dType: unrecognized XMLType: {0}'.format(XMLType)
    return dType

def parseArray(node):
    dimSizes = []
    tempList = []
    created = False    # will be set to true when the array is created
    for ele in node:
        tag = ele.tag
        if tag == 'Name':
            name = ele.text
        elif tag == 'Dimsize':
            dimSizes.append(int(ele.text)) 
        else:                                   # after the <Name> and <Dimsize> elements, there should only be data remaining
            if created == False:                # the first data element
                XMLType = tag
                dType = XMLType_to_dType(XMLType)
                created = True
            assert (tag == XMLType),'XMLType: {0} does not equal Data Type: {1}'.format(XMLType, tag)  #They should all be the same type or there is an error
            for item in ele:
                if item.tag == 'Val':
                    tempList.append(item.text)                    

    tempArray = np.reshape(np.asarray(tempList,dtype=dType),tupledimSizes))    # build the numpy array here      
    return [name,tempArray]

Tags: 数据name类型列表tagnpval数组