如何使 For 循环中的迭代更高效?

How to Make Iterating in a For Loop More Efficient?

我想使用 i 变量递增 1。应该是 [0x0]、[0x1] 和 [0x2] 应该是 [0xi],但是当我尝试这样做时它给了我一个错误。我该如何提高效率?

另外,[0x0]是什么数据类型?我以前从未遇到过这种情况。

我试过的东西:

  1. 使用“%”在另一个变量中声明一个变量
  2. 将数字放在一个数组中,然后以一个为单位进行迭代
  3. 尝试使用 "<characters> + <variable> + <characters>"
  4. 放置另一个变量

代码:


for i in range(0, 296, 1):
        time.sleep(5)
        print(" ")
        bus.write_i2c_block_data(0x2C, 0x03, [0x0])
        bus.write_i2c_block_data(0x2C, 0x01, [0x0])
        data = bus.read_byte_data(0x2C, 0x01)
        res_1 = (data / 256.0 ) * 10.0
        data = bus.read_byte_data(0x2C, 0x03)
        res_2 = (data / 256.0 ) * 10.0
        print "Resistance Channel-0 : %.2f K" %res_1
        print "Resistance Channel-1 : %.2f K" %res_2

        print(" ")
        bus.write_i2c_block_data(0x2C, 0x03, [0x1])
        bus.write_i2c_block_data(0x2C, 0x01, [0x1])
        data = bus.read_byte_data(0x2C, 0x01)
        res_1 = (data / 256.0 ) * 10.0
        data = bus.read_byte_data(0x2C, 0x03)
        res_2 = (data / 256.0 ) * 10.0
        print "Resistance Channel-0 : %.2f K" %res_1
        print "Resistance Channel-1 : %.2f K" %res_2

        print(" ")
        bus.write_i2c_block_data(0x2C, 0x03, [0x2])
        bus.write_i2c_block_data(0x2C, 0x01, [0x2])
        data = bus.read_byte_data(0x2C, 0x01)
        res_1 = (data / 256.0 ) * 10.0
        data = bus.read_byte_data(0x2C, 0x03)
        res_2 = (data / 256.0 ) * 10.0
        print "Resistance Channel-0 : %.2f K" %res_1
        print "Resistance Channel-1 : %.2f K" %res_2

0x2C0x030x00x1等都是用十六进制表示法写成的int字面值。结果值与 44301 等相同。您的函数正在将 int 值转换为其他类型.

以下完全相同:

bus.write_i2c_block_data(0x2c, 0x03, [0x1])
bus.write_i2c_block_data(44, 3, [i])  # Assuming i == 1

全部,

for i in range(0, 296, 1):
    time.sleep(5)
    print(" ")
    bus.write_i2c_block_data(0x2C, 0x03, [i])
    bus.write_i2c_block_data(0x2C, 0x01, [i])
    data = bus.read_byte_data(0x2C, 0x01)
    res_1 = (data / 256.0 ) * 10.0
    data = bus.read_byte_data(0x2C, 0x03)
    res_2 = (data / 256.0 ) * 10.0
    print "Resistance Channel-0 : %.2f K" %res_1
    print "Resistance Channel-1 : %.2f K" %res_2