Help with searching a list

Wojtek Walczak gminick at hacker.pl
Wed Nov 13 15:35:59 EST 2002


Dnia Tue, 12 Nov 2002 09:35:34 -0600, John Hunter napisał(a):
>    Tony> Python newbie needs help with searching a list of lists.
>    Tony> What is the correct way for search a list of lists ?
> You can do this by 'flattening' the list -- ie, turning into a single
> list with all the elements of the component lists (recursively).  Look
I wrote my own version of flatten. It looks good for me besides of
one thing: a declaration of list 'b'. 
Here goes a code of that function:
---
import types
b = []

def flatten(x, a=1):
   for i in x:
     if type(i) == types.ListType:
        flatten(i, 0)
     else:
        b.append(i)
   if a==1:
      return b
---

and here's an example:
---
a=[[1,[2,[3,[4,[5,[6,7]]]]]],[8,9], 10]
print flatten(a)
---
returns a list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

So, looks fine, but, is there any way of declaring 'b' list
within flatten function? At the momment its a little bit ugly ;)

-- 
[ Wojtek gminick Walczak ][ http://gminick.linuxsecurity.pl/ ]
[ gminick (at) hacker.pl ][ gminick (at) underground.org.pl  ]



More information about the Python-list mailing list