首页 > 解决方案 > 在 For 循环中打印变量

问题描述

from matplotlib.pyplot import figure
T10,T11,T12,T13 = nx.random_tree(10),nx.random_tree(11),nx.random_tree(12),nx.random_tree(13)
T = [T10,T11,T12,T13]
for t in T: 
    print("The Pruefer Code for -",  pruefer_code(t))
    fig = figure()
    axis = fig.add_subplot(111)
    nx.draw(t, **opts, ax = axis)
    

结果是:

The Pruefer Code for -  [2, 8, 1, 9, 5, 5, 6, 8]
The Pruefer Code for -  [9, 6, 10, 7, 4, 8, 10, 4, 6]
The Pruefer Code for -  [4, 1, 4, 8, 11, 11, 8, 3, 4, 8]
The Pruefer Code for -  [8, 7, 11, 4, 2, 7, 9, 1, 5, 10, 7]

加上图表 - 我将如何修改代码,所以它会说:

The Pruefer Code for - T10 [2, 8, 1, 9, 5, 5, 6, 8]
The Pruefer Code for - T11 [9, 6, 10, 7, 4, 8, 10, 4, 6]
The Pruefer Code for - T12 [4, 1, 4, 8, 11, 11, 8, 3, 4, 8]
The Pruefer Code for - T13 [8, 7, 11, 4, 2, 7, 9, 1, 5, 10, 7]

任何帮助表示赞赏:)

标签: pythonpython-3.xloopsmatplotlibnetworkx

解决方案


您可以执行以下操作:

from matplotlib.pyplot import figure
T10,T11,T12,T13 = nx.random_tree(10),nx.random_tree(11),nx.random_tree(12),nx.random_tree(13)
T = [T10,T11,T12,T13]
for i, t in enumerate(T): 
    print("The Pruefer Code for - T1{:}".format(i),  pruefer_code(t))
    fig = figure()
    axis = fig.add_subplot(111)
    nx.draw(t, **opts, ax = axis)

enuemerate返回列表中的元素以及索引 ([0,3])。然后在将当前索引添加到字符串时添加到print常量字符串将给出所需的结果(使用)。T1iformat


推荐阅读