2015-06-07 84 views
-4

我有一个函数,其中引用了'node1','node2','node3'的变量。Python - 动态命名变量

我想使第二次函数被调用,'node1'变成'node1_a',第三次'node1_b'等等。

这些'动态'变量仅在函数中被引用。如果有助于理解,我在下面有一些代码。

def marriage(husband, wife): 
    count += 1 
    node1 = pydot.Node(str(husband)) 
    node3 = pydot.Node('node_a', label='', style = 'invisible', shape = 'circle', width = '.001', height = '.001') 
    node2 = pydot.Node(str(wife)) 
    tree.add_edge(pydot.Edge(node1, node3, style = "dashed")) 
    tree.add_edge(pydot.Edge(node3, node2, style = "dashed")) 
+3

听起来像是你真正需要的是什么样的一个列表或字典的数据结构。 – refi64

+0

您可以在函数之外有一个计数器来计算该函数被调用的次数吗?如果是,则在该函数内部传递该计数器,并使用一个字典来生成变量名称作为键。 –

+0

您是否阅读过您在编写标题和问题时弹出的任何*相关问题?这个主题已经在这里覆盖了数百次... – MattDMo

回答

0
def marriage(husband, wife, method_dict): 
    count += 1 
    method_dict['node1'][count] = pydot.Node(str(husband)) 
    method_dict['node3'][count]node3 = pydot.Node('node_a', label='', style = 'invisible', shape = 'circle', width = '.001', height = '.001') 
    method_dict['node2'][count]node2 = pydot.Node(str(wife)) 
    tree.add_edge(pydot.Edge(method_dict['node1'][count], method_dict['node3'][count], style = "dashed")) 
    tree.add_edge(pydot.Edge(method_dict['node3'][count], method_dict['node2'][count], style = "dashed")) 

其中

method_dict = {{}} 
0

我认为你可以尝试字典关键是var名称和值是var值。每次调用函数时,都应更改calltimeindex。

keyName = [["node"+str(index)+"_"+ chr(i) for i in range(ord('a'),ord('z'))] for index in range(1,4)] 

varDict[keyName[varIndex][callTimeIndex]] = value