简体   繁体   English

这段代码有Python函数吗?

[英]Is there a Python function for this piece of code?

I created a graph by putting nodes in a list. 我通过将节点放在列表中来创建图形。 Node is a class with attributes 'parent', 'daughters', and 'edge'. Node是一个具有属性“parent”,“daughters”和“edge”的类。 I want to check if a symbol is in the edges of any of the daughter-nodes of a current node, and if so, to change the current node to that node. 我想检查一个符号是否在当前节点的任何子节点的边缘,如果是,则将当前节点更改为该节点。 If not, then I create a new node with that edge, and change the current node to it. 如果没有,那么我用该边创建一个新节点,并将当前节点更改为它。

I do this like this: 我是这样做的:

match = False
for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        match = True
        currentNode = daughter
if match == False:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The use of 'match' seems inelegant to me. 使用'匹配'对我来说似乎不优雅。 Is there a better syntax for checking if the edge exists among the daughters, and if so, updating the current node to that daughter, and if not, creating that node? 是否有更好的语法来检查女儿之间是否存在边缘,如果存在,则将当前节点更新为该子节点,如果不存在,则创建该节点?

You can use for/else here: 你可以在这里使用for/else

for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        currentNode = daughter
        break
else:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The else case will be executed if the for loop exited normally, ie without break 如果for循环正常退出,即没有break ,则执行else情况

You can use the for...else syntax here: 你可以在这里使用for...else语法:

for daughter in currentNode.daughters:
    if daughter.edge == currentSymbol:
        currentNode = daughter
        break
else:
    trie.append(node(currentNode, [], currentSymbol)
    currentNode = trie[-1]

The else part is executed, only if the for loop completed normally without ever breaking. 只有当for循环正常完成而没有破坏时,才会执行else部分。 So in your case, if you find a match, you break from the loop (aborting it), and the else is skipped. 因此,在您的情况下,如果您找到匹配项,则会从循环中断(中止),并跳过else And if you don't find a match, you never break from the loop, and the else is executed. 如果你没有找到匹配,你永远不会从循环中断,并执行else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM