在 Python 中将数组/列表的子集引用作为参数传递
我对 Python 有点陌生(1 天),所以也许我的问题很愚蠢.我已经看过这里,但我可以'没有找到我的答案.
I'm kind of new (1 day) to Python so maybe my question is stupid. I've already looked here but I can't find my answer.
我需要以随机大小的随机偏移量修改数组的内容.我有一个 Python API 可以为我无法修改的 USB 设备连接 DDL.有一个这样的功能:
I need to modify the content of an array at a random offset with a random size. I have a Python API to interface a DDL for an USB device which I can't modify. There is a function just like this one :
def read_device(in_array):
# The DLL accesses the USB device, reads it into in_array of type array('B')
# in_array can be an int (the function will create an array with the int
# size and return it), or can be an array or, can be a tuple (array, int)
在我的代码中,我创建了一个数组,假设为 64 个字节,我想从第 32 个字节开始读取 16 个字节.在 C 中,我会将 &my_64_array[31]
提供给 read_device
函数.在python中,如果给:
In MY code, I create an array of, let's say, 64 bytes and I want to read 16 bytes starting from the 32rd byte. In C, I'd give &my_64_array[31]
to the read_device
function.
In python, if a give :
read_device(my_64_array[31:31+16])
似乎 in_array 是对给定子集副本的引用,因此 my_64_array
没有被修改.
it seems that in_array is a reference to a copy of the given subset, therefore my_64_array
is not modified.
我能做什么?我是否必须拆分 my_64_array
并在 ??
What can I do ? Do I have to split my_64_array
and recombine it after ??
正如您所说,如果您将切片输入到函数中,它会创建切片的引用副本.
It's precisely as you say, if you input a slice into a function it creates a reference copy of the slice.
稍后添加它的两种可能方法(假设 read_device
返回相关切片):
Two possible methods to add it later (assuming read_device
returns the relevant slice):
my_64_array = my_64_array[:32] + read_device(my_64_array[31:31+16]) + my_64_array[31+16:]
# equivalently, but around 33% faster for even small arrays (length 10), 3 times faster for (length 50)...
my_64_array[31:31+16] = read_device(my_64_array[31:31+16])
所以我认为你应该使用后者.
So I think you should be using the latter.
.
如果它是一个可修改的函数(但在这种情况下不是!)你可以改变你的函数参数(一个是整个数组):
If it was a modifiable function (but it's not in this case!) you could be to change your functions arguments (one is the entire array):
def read_device(the_64_array, start=31, end=47):
# some code
the_64_array[start:end] = ... #modifies `in_array` in place
并调用 read_device(my_64_array)
或 read(my_64_array, 31, 31+16)
.