Python动态命名变量

2024-04-25 05:41:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,其中引用了'node1'、'node2'、'node3'变量。你知道吗

我想让第二次调用函数时,'node1'变成'node1\u a',第三次变成'node1\u 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"))

Tags: 函数addnodetreestyleedgestrnode1
2条回答

我想你可以试试dict键是var name,值是var value。每次调用函数时,都应该更改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
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 = {{}}

相关问题 更多 >