Python &引用;索引器:列表索引超出范围“;但它显然不是';T
首先,我是python新手,如果这是一个愚蠢的问题,我深表歉意(我有C++的背景) 我试图将串行数据(来自arduino)拆分为一个列表,并将列表中的特定元素打印到控制台中。我不会详细讨论项目细节,因为它们并不重要 原始串行数据如下所示:Python &引用;索引器:列表索引超出范围“;但它显然不是';T,python,arduino,raspberry-pi,Python,Arduino,Raspberry Pi,首先,我是python新手,如果这是一个愚蠢的问题,我深表歉意(我有C++的背景) 我试图将串行数据(来自arduino)拆分为一个列表,并将列表中的特定元素打印到控制台中。我不会详细讨论项目细节,因为它们并不重要 原始串行数据如下所示: 11111110,11111111,11111111 11111110,11111111,11111111 11111110,11111111,11111111 我尝试使用的代码是 #!/usr/bin/python import serial, st
11111110,11111111,11111111
11111110,11111111,11111111
11111110,11111111,11111111
我尝试使用的代码是
#!/usr/bin/python
import serial, string
output = " "
ser = serial.Serial('/dev/ttyUSB0', 31250, 8, 'N', 1, timeout=1)
while True:
print "----"
while output != "":
output = ser.readline()
outList = output.strip().split(',')
print outList[1]
output = " "
我得到一个错误:
Traceback (most recent call last):
File "serialtest.py", line 12, in <module>
print outList[1]
IndexError: list index out of range
我可以让
print outList[0]
工作,它可以打印11111110
。这表明它可能不喜欢11111111
?您需要测试输出是否为空字符串,然后再尝试拆分它
您还需要在测试它之前剥离大纲
,而不仅仅是在拆分它时
while True:
print "----"
while True:
output = ser.readline().strip()
if output == "":
break
outList = output.split(',')
print outList[1]
每行输入之间真的有一个空行吗?似乎是一个值,列表中索引的末尾应该有一个逗号
,因为在放置输出时没有逗号,列表中只有一个值。使用打印(outList)时,您确定每行之间没有看到['']
?就我个人而言,我认为这是一个学习如何使用python调试器的案例,只是逐步执行以确保每个变量都符合预期。从print(outList)
显示的结果没有意义。这是三个单独的列表,不能是split()
的结果。
while True:
print "----"
while True:
output = ser.readline().strip()
if output == "":
break
outList = output.split(',')
print outList[1]