我正在使用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中的示例调用中,函数返回一个列表,所以我可以假设这种行为是正常的。
答案 0 :(得分:2)
该函数返回(似乎是)字典...
不,这是列表中的字典。方括号是值的一部分。
>>> [{'foo':'bar'}][0]
{'foo': 'bar'}