Skip to main content
 首页 » 编程设计

Python:执行此循环的 Pythonic 方式是什么

2025年05月04日15dyllove98

执行此循环的 pythonic 方法是什么。我正在尝试选择一个将返回子树而不是根的随 secret 钥。因此:'parent == None' 不可能为真。 “isRoot==True”也不可能是真的。

thekey = random.choice(tree.thedict.keys()) 
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == True): 
        thekey = random.choice(tree.thedict.keys()) 
....... 

编辑:现在有效

请您参考如下方法:

key = random.choice([key for key, subtree in tree.thedict.items() 
                         if subtree.parent and not subtree.isRoot]) 

(评论和问题编辑后更正)