Dealing with Lists

Dave Angel davea at davea.name
Tue Sep 10 22:24:44 EDT 2013


On 10/9/2013 22:14, Steven D'Aprano wrote:

> On Tue, 10 Sep 2013 14:08:45 -0700, stas poritskiy wrote:
>
>> Greetings to all!
>> 
>> i ran into a little logic problem and trying to figure it out.
>> 
>> my case is as follows:
>> 
>> i have a list of items each item represents a Group
>> i need to create a set of nested groups,
>> so, for example:
>> 
>> myGroups = ["head", "neck", "arms", "legs"]
>
>
> What is the rule for grouping these items? Below, you suggest:
>
> head encloses neck
> neck encloses arms
> arms encloses legs
>
> which seems rather strange. But if it is *always* the case that each item 
> encloses the next item:
>
> def print_nested_list(alist):
>     spaces = ' '*4
>     for level, item in enumerate(alist):
>         if level != 0:
>             indent = spaces*(level-1) + '  '
>             print (indent + '|_>'),  # note comma
>         print item
>
>
> which gives us this:
>
> py> print_nested_list(['head', 'neck', 'arms', 'legs'])
> head
>   |_> neck
>       |_> arms
>           |_> legs
>
>
> as requested.
>
>

Very nice.  But what I want to know is how did you know that Stan (the
OP) wanted his printed output to be formatted that way?  He said:

>>>>> i need to create a set of nested groups,
and
>>>>> store each of the first elements of a par, so I can reference to them as to a parent of another group.


-- 
DaveA





More information about the Python-list mailing list