简体   繁体   中英

How to create and traverse decision tree in Python

I am trying to create a Tree in python that looks like this diagram:

图表

How do I write code in Python to create this tree and find a given "answer" or leaf node, given gender and color.

For example:

Input: { Gender : "Female", Color : "Green" }

Output: "Message 5"

I am going to add more levels and nodes, so I trying to create a tree representation rather than a bunch of "if" statements, since that could be messy.

You can create the tree in a dict structure, eg:

tree = {'Male': {'Red': 'Message 1', 'Green': 'Message 2', 'Blue': 'Message 3'}, 
        'Female': {'Red': 'Message 4', 'Green': 'Message 5', 'Blue': 'Message 6'}}

Then traversing this tree is nothing more than key lookups, eg:

In []:
i = {'Gender' : "Female", 'Color' : "Green" }
tree[i['Gender']][i['Color']]


Out[]:
"Message 5"

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