将串行数据添加到列表会导致 IndexError

Adding serial data to list causes IndexError

我正在从 arduino 读取串行数据,然后过滤它们,然后将数据放入列表中。

def readSerial():
    global after_id, found_coordinate, coordinate, sensors
    while ser.in_waiting:
            ser_bytes = ser.readline()
            ser_bytes = ser_bytes.decode("utf-8")
            if "SENSOR COORDINATE" in ser_bytes:
               found_coordinate = True
               coordinate = int(ser_bytes.split("=")[1].strip())
               print("Coordinate: ",coordinate)
            if "MEASURED RESISTANCE" in ser_bytes and found_coordinate:
               found_coordinate = False
               resistance = float(ser_bytes.split("=")[1].split("kOhm")[0].strip())
               print("Resistance: ",resistance)
               sensors[coordinate].append(resistance) # Append the resistance value, to the appropriate sensor list
    after_id=root.after(50,readSerial)

我过滤数据,如果我在一行中看到文本“SENSOR COORDINATE”,我会解析该数据。 然后我还获取该传感器的电阻,并使用 append() 行,将该值放入列表中,索引为我之前获取的电阻坐标值。

然而,在我收到几次数据后,我遇到了 IndexError: list index out of range

这是完整的终端输出和错误:

Coordinate:  0
Resistance:  3.2
Coordinate:  1
Resistance:  3.2
Coordinate:  2
Resistance:  3.23
Coordinate:  3
Resistance:  3.31
Coordinate:  4
Resistance:  3.3
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__i
nit__.py", line 1883, in __call__
    return self.func(*args)
  File "C:\Users\User1\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__i
nit__.py", line 804, in callit
    func(*args)
  File "tkinterWithPortsExperiment.py", line 103, in readSerial
    sensors[coordinate].append(resistance) # Append the resistance value, to the
 appropriate sensor list
IndexError: list index out of range

在第五次迭代中,coordinate == 4,它尝试访问 sensors 的第 4 个索引。由于 sensors 只有四个元素(最大索引为 3),它会提高你得到的 IndexError

在访问它的某些索引之前,您可以检查检查 sensors 长度的逻辑:

if "MEASURED RESISTANCE" in ser_bytes and found_coordinate:
    found_coordinate = False
    resistance = float(ser_bytes.split("=")[1].split("kOhm")[0].strip())
    if coordinate < len(sensors):
        sensors[coordinate].append(resistance)
    else:
        # do some other logic