我正在尝试实现一个函数(make_q),该函数返回使用make_q获得的参数(P)生成的函数(Q)列表。 Q是一个依赖于n(=len(P))的变量,使得Q函数是相似的,所以可以在for循环中完成,但是这里有一个catch,如果我在循环中命名函数,它们都有相同的地址,所以我只得到最后一个Q,有没有绕过这个? 这是我的代码,
def make_q(self):
Temp_P=[p for p in self.P]
Q=()
for i in range(self.n-1):
p=min(Temp_P)
q=max(Temp_P)
index_p=Temp_P.index(p)
index_q=Temp_P.index(q)
def tempQ():
condition=random.random()
if condition<=(p*self.n):
return index_p
else:
return index_q
Temp_Q=list(Q)
Temp_Q.append(tempQ)
Q=tuple(Temp_Q)
q-=(1-p*self.n)/self.n
Temp_P[index_q]=q
Temp_P.pop(index_p)
return Q
test.Q
(<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>,
<function __main__.Test.make_q.<locals>.tempQ()>)
我还试图使它们成为一个元组,这样它们就有不同的地址,但没有成功。 有没有一种方法将函数(tempQ)命名为dynamic
,就像tempqi
请尝试通过格式化字符串,例如:“function_{}。format(name)”另外,您希望您的输出是什么样子的?