walking a list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mr.happy

    walking a list

    Hi all,

    I have this little question, basicly i solved it already by writing a
    little bit of code for it (using recursion), but still i am wondering if
    there is a shorter ways to do things (like 1 or 2 commands).

    the problem is this, imagine i have a list:

    list = [1, 2, [3, 2], 5, [6, 5, 4]]

    if i print out this list using 'for element in list: print element,'
    it will show me the following:

    1
    2
    [3, 2]
    5
    [6, 5, 4]

    but what i really want to show is:

    1
    2
    3
    2
    5
    6
    5
    4

    What i want to do is run through the list and when i get back a list run
    through that list as well (and if that list contains a list run through it
    again etc.).

    all suggestions are welcome, i'm ready to learn from the pro's ;)

    --
    One monk said to the other, "The fish has flopped out of the net! How will it
    live?" The other said, "When you have gotten out of the net, I'll tell you."

  • Jeff Epler

    #2
    Re: walking a list

    def print_or_recurs e(l):
    for i in l:
    if isinstance(i, list): print_or_recurs e(i)
    else: print i

    print_or_recurs e([1,2,[3,2],5,[6,5,4]])

    Jeff

    Comment

    • mr.happy

      #3
      Re: walking a list

      On Fri, 23 Apr 2004 13:21:43 -0500, Jeff Epler wrote:
      [color=blue]
      > if isinstance(i, list): print_or_recurs e(i)[/color]

      great! thanks, i didn't know 'isinstance' existed.
      what i did was the following:

      if 'list' in str(type(list)) :

      it worked as well :)

      --
      One monk said to the other, "The fish has flopped out of the net! How will it
      live?" The other said, "When you have gotten out of the net, I'll tell you."

      Comment

      Working...