简体   繁体   中英

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. 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.

Here's a photo from the book that I'm attempting to recreate in a python object:

数学对象

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.

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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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