这肯定不是特定于 python 的问题,但我正在寻找特定于 python 的答案——如果有的话。它是关于将具有大量变量的代码块放入函数(或类似的?)中。让我假设这段代码
##!/usr/bin/env python
# many variables: built in types, custom made objects, you name it.
# Let n be a 'substantial' number, say 47.
x1 = v1
x2 = v2
...
xn = vn
# several layers of flow control, for brevity only 2 loops
for i1 in range(ri1):
for i2 in range(ri2):
y1 = f1(i1,i2)
y2 = f2(i1,i2)
# Now, several lines of work
do_some_work
# involving HEAVY usage and FREQUENT (say several 10**3 times)
# access to all of x1,...xn, (and maybe y1,y2)
# One of the main points is that slowing down access to x1,...,xn
# will turn into a severe bottleneck for the performance of the code.
# now other things happen. These may or may not involve modification
# of x1,...xn
# some place later in the code, again, several layers of flow control,
# not necessarily identical to the first occur
for j1 in range(rj1):
y1 = g1(j1)
y2 = g2(j1)
# Now, again
do_some_work # <---- this is EXACTLY THE SAME code block as above
# a.s.o.
显然,我想将“do_some_work”放入函数之类的东西(或者更好的东西?)。
在 python 中执行此操作的最高效方法是什么
没有带有大量令人困惑的参数的函数调用
没有性能有损的间接访问 x1,...,xn (例如,通过将它们包装到另一个列表、类或类似物中)
在函数 do_some_work(...) 中不使用 x1,...,xn 作为全局变量
我不得不承认,我总是发现自己回到了全球。