繁体   English   中英

返回指定为列表的类型字典

[英]Return of type dictionary assigned as list

我正在使用Labjack进行python 2.7.3 32bit的数字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中的示例调用中,函数返回一个列表,因此我可以假设这种行为是正常的。

该函数返回(似乎是)字典...

不,这是列表中的字典。 方括号是值的一部分。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM