返回指定为lis的类型字典

2024-04-29 00:07:47 发布

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

我正在使用Labjack与python 2.7.3 32位进行一些数字I/O,遇到以下问题:

这是我调用的labjack u6函数:

    class PortStateRead(FeedbackCommand):
    """
    PortStateRead Feedback command

    Reads the state of all digital I/O.

    >>> d.getFeedback( u6.PortStateRead() )
    [ { 'FIO' : 10, 'EIO' : 0, 'CIO' : 0 } ]
    """
    def __init__(self):
        self.cmdBytes = [ 26 ]

    def __repr__(self):
        return "<u6.PortStateRead()>"

    readLen = 3

    def handle(self, input):
        return {'FIO' : input[0], 'EIO' : input[1], 'CIO' : input[2] }

函数正在返回(看起来是)一个字典,但是当我将这个返回赋值给一个变量时,它被赋值为一个列表。你知道吗

    >>> import u6
    >>> handle = u6.U6()
    >>> x = handle.getFeedback(u6.PortStateRead())
    >>> x
    [{'CIO': 15, 'FIO': 255, 'EIO': 255}]
    >>> x['FIO']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: list indices must be integers, not str

将x[0]赋给一个新变量将作为字典进行赋值

    >>> y = x[0]
    >>> y['FIO']
    255

有人能给我解释一下这种行为吗?你知道吗

在docstring中的示例调用中,函数返回一个列表,因此我可以假设这种行为是正常的。你知道吗


Tags: 函数self列表inputreturn字典deffio
1条回答
网友
1楼 · 发布于 2024-04-29 00:07:47

The function is returning (what appears to be) a dictionary...

不,这是一本单子里的字典。方括号是值的一部分。你知道吗

>>> [{'foo':'bar'}][0]
{'foo': 'bar'}

相关问题 更多 >