Dealing with Lists

Peter Otten __peter__ at web.de
Wed Sep 11 12:17:58 EDT 2013


stas poritskiy wrote:

By now your post consists of over 1300 lines, most of them containing 
nothing but quoting marks. Please be courteous to your readers and avoid 
that.

https://wiki.python.org/moin/GoogleGroupsPython

may be helpful.

> ok, while writing this, i figured out where those elements are located,
> so each element is always at the position 0, and to get deeper i have to
> follow something similar to this chopGrp = [[u'arms', [u'a', [u'super',
> [u'group', [u'type', [u'is', [u'here']]]]]]]
> 
> print chopGrp[1][1][1][1][0] (this would get me "type" from the list)
>>>>type
> 
> this is getting somewhere, now, i am confused what type of iteration loop
> i should make, where each element is being called by itself,
> 
> so i could reference the previous element as its Parent.
> so if i make this manually as a pseudo code:
> 
> chopGrp[0] #gets me "arms"
> print "Parent is: " + chopGrp[0]
> chopGrp[1][0] #gets me "a"
> print "Child is: " + chopGrp[1][0]
> 
> and the next iteration should take the
> 
> chopGrp[1][0] and make it a parent of chopGrp[1][1][0]

Again, be courteous and give actual self-contained runnable Python code. I 
doubt that anyone can make much of the above
 
> any hints?

My impression is that much of your confusion stems from using generic lists 
where items in different positions have a different meaning for different 
posters and it is difficult to keep track of what's what. I suggest you bite 
the bullet and go for a class-based approach. Then, when you talk about 
"children" or "parent" it is clear that you find them in the Node's 
attribute of the same name.

Proceed to express your tasks in plain English as clearly as you can, and 
only then try to transform them into code.

To get you started here's what a simple tree might look like:

$ cat tree.py 
from __future__ import print_function

from collections import OrderedDict as Children

class Node:
    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent
        self.children = Children()
        if parent is not None:
            self.parent.children[name] = self

    def show(self, level=0):
        print("    " * level, self.name, sep="")
        for child in self.children.values():
            child.show(level + 1)

class Tree(Node):
    def __init__(self):
        Node.__init__(self, None)

    def ensure(self, path):
        """Add node with all intermediate nodes"""
        node = self
        for name in path:
            try:
                node = node.children[name]
            except KeyError:
                node =  Node(name, node)
        return node

    def show(self, level=0):
        for child in self.children.values():
            child.show()

if __name__ == "__main__":
    data = """\
plant flower tulip
plant flower lily
animal mammal cat
animal mammal zebra
animal reptile snake
animal reptile snake python
animal reptile snake boa
"""

    paths = [line.split() for line in data.splitlines()]

    tree = Tree()
    for path in paths:
        tree.ensure(path)
    tree.show()


And here's the output of the demo:

$ python tree.py
plant
    flower
        tulip
        lily
animal
    mammal
        cat
        zebra
    reptile
        snake
            python
            boa





More information about the Python-list mailing list