ser = serial.Serial('/dev/ttyACM0', baudrate=9600,timeout=1)
while True:
line = ser.readline().decode('utf-8').rstrip()
value = [float(x) for x in line.split()]
print(value)
print(value[0])
print(value[1])
print(value[2])
print(value[3])
这是我串行读取一行的代码,但有时从串行读取的数据没有完成
[10.2, 27.2, 9.8, 12.6]
10.2
27.2
9.8
12.6
[]
Traceback (most recent call last):
File "/home/pi/Desktop/Serial/RXTX Arduino.py", line 27, in <module>
print(value[0])
IndexError: list index out of range
如果我想将数组中的值分配给诸如
之类的变量,如何避免索引错误read0 = value[0]
read1 = value[1]
read2 = value[2]
read3 = value[3]
答案 0 :(得分:1)
一种解决方案是简单地处理异常并停止填充变量(在预先为它们提供一些标记值之后)。这可以通过以下方式完成:
read0, read1, read2, read3 = None, None, None, None
try:
read0 = value[0]
read1 = value[1]
read2 = value[2]
read3 = value[3]
except IndexError:
pass
例如,如果您的 value
最终只有两个条目,则 read2
赋值会发生异常,并且 read2
和 read3
仍将被设置到None
。您想如何处理尚不清楚,因此您需要考虑一下。
另一种解决方案是预先简单地检查长度并将少于四个项目的列表作为特殊情况处理。那将是这样的:
read0, read1, read2, read3 = None, None, None, None
if len(value) > 0: read0 = value[0]
if len(value) > 1: read1 = value[1]
if len(value) > 2: read2 = value[2]
if len(value) > 3: read3 = value[3]
当然,您总是可以保留数组中的项目并从那里使用它们,而不是转移到四个不同的变量。