I'm still pr开发者_开发百科etty new to Python, so forgive me this question if it's stupid. I could not find an answer through Google...
I am using PyFFTW in my code, which has a planning stage, where you pass it the two variables (source/destination), that your transforming from/to. It will then, when you call the FFT operate on the exact memory space, where those variables were located during the planning stage. Thus any operations done on the variables will need to be done, so that the location in memory of these two variables do not change.
I found the operators *=
, +=
, etc., which do this for standard mathematical operators.
However in my program I need to apply a function to the variable, which should return it to the same memory location.
How to do this?!
I initially used slicing in the following way:
a[:] = func(a)[:]
However I just realized, that this is extremely slow (my code is about 10% slower). So does anybody know how to go about this?
Any help is very appreciated. Thanks in advance!
Your variable is a mutable type, so your function can just operate on it directly.
You still won't be able to use functions and operators that are going to create copies and/or make new assignments (the same ones you couldn't use already), but direct mutations of the argument of your function will be visible outside the function.
how about using local value and referring it to the global value. I guess it could make faster...
global a
a = []
def test():
global a
b = [1,2,3,4]
a = b
....
um.. I also would have to test it with cProfiler
Is this something you are trying to do?
def time10(a):
""" multiple the elements by 10 in-place """
for i in xrange(len(a)):
a[i] *= 10
# returning a is optional. I think it maybe useful for use to chain the operation
return a
>>> a = range(10)
>>> time10(a)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> a
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> b = range(10)
>>> time10(time10(b))
[0, 100, 200, 300, 400, 500, 600, 700, 800, 900]
>>> b
[0, 100, 200, 300, 400, 500, 600, 700, 800, 900]
>>>
Your original code copy the array after it returns. It is usually not a useful practice and contribute to your slower runtime.
So in the end I could not find a satisfying solution to the problem. I initially ended up using the solution proposed by delnan above
a[:] = func(a)[:]
and preallocating the arrays of a certain size. Sorry for adding this as my answer, as I couldn't figure out how to/if it's possible accept delnans comments as the answer...
精彩评论