避免 IndexError : 列表索引超出范围

穆罕默德·阿里夫丁
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]
暗黑破坏神

一种解决方案是简单地处理异常并停止填充变量(在预先为它们提供一些标记值之后)。这可以通过以下方式完成:

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分配,都read2read3仍然会被设置为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]

当然,你总是可以离开该项目在数组中,并利用它们从那里,而不是转移到四个不同的变量。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章