Python:执行这个循环的Pythonic方式是什么?
在Python中,怎么用更优雅的方式来做这个循环呢?我想随机选择一个键,这个键能返回一个子树,而不是根节点。所以:'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())
.......
补充:现在可以用了
8 个回答
1
在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种特定的格式,这个过程叫做“解析”。
解析的意思就是把复杂的东西变得简单易懂。比如说,如果你有一段文本,里面包含了很多信息,解析的过程就是把这些信息提取出来,整理成一个结构化的形式,这样程序就能更方便地使用这些数据了。
在实际操作中,解析可以通过一些工具或者库来完成,这些工具可以帮助我们快速地处理数据,避免手动去一一分析。这样,我们就能节省时间,专注于其他更重要的编程任务。
总之,解析就是把复杂的数据变得简单明了,让程序能够轻松地理解和使用这些数据。
thekey = random.choice(tree.thedict.keys())
parent = thedict[thekey].parent
while parent is None or parent.isRoot:
thekey = random.choice(tree.thedict.keys())
parent = thedict[thekey].parent
3
获取一个随机的子树,但不能是根节点
not_root_nodes = [key, node for key,node in tree.thedict.iteritems() if not ( node.parent is None or node.isRoot)]
item = random.choice( not_root_nodes )
3
key = random.choice([key for key, subtree in tree.thedict.items()
if subtree.parent and not subtree.isRoot])
(在评论和问题编辑后进行了修正)