Dealing with Lists
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Sep 10 22:14:06 EDT 2013
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.
--
Steven
More information about the Python-list
mailing list