在python中循环增加i

时间:2014-04-07 16:57:39

标签: python loops printing digraphs

我可以以某种方式创建一个循环,遍历我的一些代码,并且每次循环a时都会增加,并打印出底部的行吗?

a=0

str1 = h[a]


dG = nx.DiGraph()

for i, word in enumerate(str1):

    try:
        next_word = str1[i + 1]
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
        if not dG.has_node(next_word):
            dG.add_node(next_word)
            dG.node[next_word]['count'] = 0

        if not dG.has_edge(word, next_word):
            dG.add_edge(word, next_word, weight=maxint - 1)
        else:
            dG.edge[word][next_word]['weight'] -= 1
    except IndexError:
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
    except:
        raise

for node in dG.nodes():
print '%s:%d\n' % (node, dG.node[node]['count'])   

更新

ha[a]中的

str1=h[a包含一堆这样的列表:

['14th_century', 'Time', 'Isaac_Newton', 'Rainbow']
['14th_century', 'Time', 'Light', 'Rainbow']
['14th_century', 'Time', 'Light', 'Color', 'Rainbow']

我在想是否可以在a中运行一个增加str1 = h[a]的循环,我可以得到这个输出:

Rainbow:2

Color:1

Isaac_Newton:1

Time:3

Light:2

14th_century:3

但是现在它只计算我选择a的一行?这有什么意义吗?

1 个答案:

答案 0 :(得分:1)

def printStuff(labels,dG):
    for index, node in enumerate(dG.nodes()):
        print '%s:%d\n' % (labels[index],dG.node[node]['count'])   


dG = nx.DiGraph()

for i, word in enumerate(str1):

    try:
        next_word = str1[i + 1]
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
        if not dG.has_node(next_word):
            dG.add_node(next_word)
            dG.node[next_word]['count'] = 0

        if not dG.has_edge(word, next_word):
            dG.add_edge(word, next_word, weight=maxint - 1)
        else:
            dG.edge[word][next_word]['weight'] -= 1
    except IndexError:
        if not dG.has_node(word):
            dG.add_node(word)
            dG.node[word]['count'] = 1
        else:
            dG.node[word]['count'] += 1
    except:
        raise

    printStuff(h[i], dG)