Python - 动态命名变量

时间:2015-06-07 20:16:06

标签: python variables

我有一个函数,其中引用了'node1','node2','node3'的变量。

我想这样做,以便第二次调用该函数,'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"))

2 个答案:

答案 0 :(得分:0)

我认为你可以试试dict,键是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

答案 1 :(得分: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 = {{}}