使用Ctypes和替换数组值

时间:2019-01-14 17:00:14

标签: python ctypes

我正在使用此处找到的ctypes修改python包装器: https://github.com/Grix/helios_dac/blob/master/sdk/examples/python/linux_example.py

我正在使用可变性的逻辑,并通过引用普通的python代码进行传递,并且如果更改第33和39行,该代码将不再起作用:

for j, f in enumerate(frames[i]):
    if (j < 500):
        x = round(j * 0xFFF / 500)
    else:
        x = round(0xFFF - ((j - 500) * 0xFFF / 500))

    f = HeliosPoint(int(x),int(y),255,255,255,255)

有人可以解释为什么吗? f不等于frame [i] [j]吗?

1 个答案:

答案 0 :(得分:0)

根据[Python 3]: The for statement

  

for循环将分配给目标列表中的变量。这将覆盖所有先前指配到这些变量包括在套件中的for循环的制备:

for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range

我将提供一个简单的例子,然后延伸到你的。

>>> l = [1, 2, 3]
>>> for i in l:
...     i += 5
...     print(i)
...
6
7
8
>>> print(l)
[1, 2, 3]

在相同的代码但不循环将是:

>>> i = l[0]
>>> i += 5
>>> print(i)
6
>>> i = l[1]
>>> i += 5
>>> print(i)
7
>>> i = l[2]
>>> i += 5
>>> print(i)
8
>>> print(l)
[1, 2, 3]

如图所示,为循环变量分配另一个值,不更改原始值。这可以把更简单:

>>> some_variable = 1
>>> some_variable
1
>>> some_other_variable = some_variable
>>> some_other_variable  # Here it will have value 1
1
>>> some_other_variable = 2  #  The value will change, but it won't affect `some_variable`
>>> some_other_variable
2
>>> some_variable  # Its value is unchanged
1

要在迭代时更改列表中的值,一种方法是使用枚举(因为您已经在代码中使用了它):

>>> l
[1, 2, 3]
>>> for idx, elem in enumerate(l):
...     l[idx] = elem + 5
...
>>> print(l)
[6, 7, 8]

应用同样的原理你的问题:在你的代码段的最后一行:

f = HeliosPoint(int(x),int(y),255,255,255,255)

应成为:

frames[i][j] = HeliosPoint(int(x), int(y), 255, 255, 255, 255)