+ Reply to Thread
Page 1 of 2
1 2 LastLast
Results 1 to 10 of 14

Thread: iterating through nested lists - flattening

  1. #1

    iterating through nested lists - flattening

    Hi guys,

    does anyone know a fast and efficient way to iterate through a nested list within a nested list withing a nested list etc etc which you don't know the overall length?

    I've put something like this together to check what is each location in a list (list, tuple, string, int)

    PYTHON Code:
      arrPts = []
      arrPts.append([2,3,4,5])
      arrPts.append("hello")
      arrPts.append(6)
      arrPts.append([7,[8,9],10])
       
       
      for i in arrPts:
              if type(i) == type(list()):
                  print "nested LIST found"
                  for j in i :
                      if type(j) == type(list()):
                          print "nested LIST found"
                          for k in j :
                              if type(k) == type(list()):
                                  print "nested LIST found"
                              else:
                                  print k
                      else:
                          print j
                         
              elif type(i) == type(tuple()):
                  print "TUPLE"
                  for j in i:
                      print j
              elif type(i) == type(str()):
                  print i
              elif type(i) == type(int()):
                  print i

    yet as u can see going from 'i' to 'j' to 'k' and son on can be endless, especially if you don't know the depth of the list.

    Any suggestions? I think it has something to do with flattening the list, with the yield command?


    thanks

    Pav

  2. #2
    Senior Member Steve Baer's Avatar
    Join Date
    Apr 2010
    Location
    Seattle
    Posts
    1,464
    Blog Entries
    19
    you could use a recursive function for this. Just jotting down a function here without testing so it may have a typo

    Python Code:
      arrPts = []
      arrPts.append([2,3,4,5])
      arrPts.append("hello")
      arrPts.append(6)
      arrPts.append([7,[8,9],10])
       
      def WalkList( thelist ):
          for item in thelist:
              if item is list:
                  print "nested LIST found"
                  WalkList(item)
              elif item is tuple:
                  print "TUPLE"
                  WalkList(item)
              else:
                  print item
       
      WalkList(arrPts)

  3. #3

    iterating, flattening list

    Hi Steve and thanks,

    what you wrote will iterate through every level of sub_list on a basis of "all the possible sublists at position 0", then "all the possible sublists at the position 1" etc.

    what if i want to iterate through :
    all elements in root lists, then through all elements in level 1 sublists , then through level 2 sublists etc? have you got anything to suggest for that? I hope i'm explaining this good enough.

    thanks again

    Pav
    Last edited by pavlos03; 10-16-2012 at 09:19 PM.

  4. #4
    Senior Member Steve Baer's Avatar
    Join Date
    Apr 2010
    Location
    Seattle
    Posts
    1,464
    Blog Entries
    19
    I'm sure I could answer this if you gave me a sample of input and what the output order you want is

  5. #5
    Hi Pavlos03,
    does this work for you ?

    Python Code:
      def WalkList2(thelist):       
          def WalkListRecursive(thelist):       
              # first split into iterable and non iterable objects
              collections = []   
              for item  in thelist:
                  if hasattr(item,"__iter__"): # returns true for list , tuples, .net-arrays and other collections but not Strings
                      collections.append(item) #save for iterating later
                  else:
                      result.append(item) #first collect all items of this level nesting
       
              #second go to next level of nesting
              for collection  in collections:
                  WalkListRecursive(collection)
         
          result = []
          WalkListRecursive(thelist)
          return result
         
      arrPts = []
      arrPts.append([2,3,4,5])
      arrPts.append("hello")
      arrPts.append(6)
      arrPts.append([7,["vf","xx"],10])
       
      unnested = WalkList2(arrPts)
      print unnested

    you can also look here for probably more efficient implementations:
    http://stackoverflow.com/questions/2...ists-in-python
    Last edited by Goswin; 10-17-2012 at 02:03 PM.

  6. #6
    if the order of the resulting list is not relevant you can also use this:

    Python Code:
      def WalkList3(thelist):       
          def WalkListRecursive(thelist):
              for item  in thelist:
                  if hasattr(item,"__iter__"): # returns true for list , tuples, .net-arrays and other collections but not Strings
                      WalkListRecursive(item) # recursive call
                  else:
                      result.append(item)
       
          result = []
          WalkListRecursive(thelist)
          return result 
             
             
      arrPts = []
      arrPts.append([2,3,4,5])
      arrPts.append("hello")
      arrPts.append(6)
      arrPts.append([7,["vf","xx"],10])
       
      unnested = WalkList3(arrPts)
      print unnested

  7. #7
    Hi Steve, in regard to your first code posting:

    Python Code:
      a = [1,2,3]
      print a is list # returns False for me, not True
       
    Last edited by Goswin; 10-17-2012 at 04:49 PM.

  8. #8
    This will work though:

    Python Code:
      a = [1,2,3]
      print type(a) is list

    Ps. How do you guys post source code with syntax highlighting and all that jazz?
    Last edited by AHD; 10-17-2012 at 05:15 PM. Reason: Added code highlighting

  9. #9

  10. #10
    Sweet, that was easy. Thanks Goswin.

+ Reply to Thread

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts