【问题标题】:How to add values in Python Array on Run-time?如何在运行时在 Python 数组中添加值?
【发布时间】:2020-02-13 15:10:36
【问题描述】:

我有一个程序可以读取 Arduino Board 的数字引脚。如果数字引脚为 PULLUP(关键字),则电路板返回输出,表示数字引脚为“b'1'”,如果 PULLDOWN(关键字)表示数字引脚为“关闭”,则为“b'0'”。如果输出为 b'0',我将在数组中添加 0,如果输出为 b'1',则添加 1,最后打印它们。但它给出了错误。代码如下:

from serial import Serial
import time

arduinodata = Serial("COM4",9600)
a=1
i=0
current=0
data=[]
while (a<9):
    binary = arduinodata.read()
    if(binary==b'1'):
        data[i].append(1)
        i=i+1
        a=a+1
    if(binary==b'0'):
        data[i].append(0)
        current=i
        i=i+1
        a=a+1

for b in data:
    print(data[b])

错误:

Traceback (most recent call last):    
    File "GettingBitStatus.py", line 12, in <module>       
 data[i].append(1)    
IndexError: list index out of range

【问题讨论】:

  • 错误是什么?
  • 回溯(最近一次调用最后一次):文件“GettingBitStatus.py”,第 12 行,在 data[i].append(1) IndexError: list index out of range

标签: python arrays list input arduino


【解决方案1】:

您正在尝试对列表中的项目使用 append 方法,而不是列表本身。

尝试以下方法:

from serial import Serial
import time

arduinodata = Serial("COM4",9600)
a=1
i=0
current=0
data=[]
while (a<16):
    binary = arduinodata.read()
    if(binary==b'1'):
        data.append(1)
        i=i+1
    if(binary==b'0'):
        data.append(0)
        current=i
        i=i+1

for b in data:
    print(b)

使用列表推导的更 Pythonic 的方法类似于

from serial import Serial
arduinodata = Serial("COM4",9600)
data = [ int(arduinodata.read()) for _ in range(16) ]         

【讨论】:

  • 我很难相信它给出了确切的错误。因为这个方案去掉了对数组中某个元素的调用..
【解决方案2】:

问题出在以下几行:

data[i].append(1)
data[i].append(0)

下面是写这些行的正确方法:

data.append(1)
data.append(0)

没有错误的最终代码:

from serial import Serial
import time

arduinodata = Serial("COM4",9600)
a=1
i=0
current=0
data=[]
while (a<9):
    binary = arduinodata.read()
    if(binary==b'1'):
        data.append(1)
        a=a+1
    if(binary==b'0'):
        data.append(0)
        current=i
        a=a+1

for b in data:
    print(b)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多