简体   繁体   English

在Python中递归遍历对象

[英]Iterate over object recursively in Python

I'm studying this book called "A Field Guide to Genetic Programming" for fun. 我正在研究这本名为《遗传编程领域指南》的书,很有趣。 The book uses math structures which to me looks a whole lot like objects in Python. 这本书使用的数学结构对我来说看起来很像Python中的对象。 So I'm trying to figure out how to iterate over an object in Python without knowing the names of the keys or child objects in advance. 因此,我试图找出如何在Python中迭代对象而又不事先知道键或子对象的名称的方法。

Here's a photo from the book that I'm attempting to recreate in a python object: 这是我试图在python对象中重新创建的书中的照片:

数学对象

Right now, I'm just trying to get them to print to console. 现在,我只是想让它们打印到控制台。 Below is what I have tried. 下面是我尝试过的。

#!/usr/bin/python

def iterate(object):
    for item in object:
        print str(object)
        iterate(object)

object = {}
object['+'] = []
object['+'].append(5)
object['+'].append(3)

iterate(object)

In the object, I'm just trying to iterate over a very simple math structure: 在对象中,我只是尝试迭代一个非常简单的数学结构:

{"+": [5, 3]}

Which should equate to 5 + 3 eventually, but I haven't figured out how to iterate over the object without knowing it's key names. 最终应该等于5 + 3,但是我还没有弄清楚如何在不知道键名的情况下迭代该对象。

Any help is appreciated, thanks. 任何帮助表示赞赏,谢谢。

What you are attempting to create is a binary tree, ie a structure that contains a node and two children. 您试图创建的是一个二叉树,即一个包含一个节点和两个孩子的结构。 For the dictionary you have created, you can iterate using a for-loop and dict.items() : 对于您创建的字典,可以使用for循环和dict.items()进行迭代:

d = {"+": [5, 3]}
for parent, children in d.items():
    print(parent, children)

However, for a more generic, recursive solution: 但是,对于更通用的递归解决方案:

d = {"+": [5, 3]}
def flatten(s):
   for i in s:
      if isinstance(i, int) or isinstance(i, str):
         print(i)
      else:
         flatten(i)

flatten(d.items())

Output: 输出:

'+'
 5
 3

did not check the code but that might help: 没有检查代码,但这可能会有所帮助:

def iterate(object):
    if isinstance(object,dict):
        for key, item in object.items():
            leftItem = item[0]
            rightItem = item[1]
            if isinstance(leftItem,dict):
                return iterate(item)
            else:
                return str(leftItem) + str(key) + str( iterate(rightItem) )
    else:
        return object

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

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