Flatten... or How to determine sequenceability?
Thomas Wagner
gluon at web.de
Fri May 25 11:58:09 EDT 2001
Hi Noel,
try this ...:
import types
def additem(li, item):
if type(item)==types.ListType:
for litem in item:
additem(li,litem)
else:
li.append(item)
def flatten(li):
dest = []
for item in li:
additem(dest,item)
return dest
# source list
src = ['1', [2, ['a', 'b']], 4]
# destination list ...
dest = flatten(src)
Regards,
Thomas
"Noel Rappin" <noelrap at yahoo.com> schrieb im Newsbeitrag
news:mailman.990802119.12058.python-list at python.org...
> I'm writing code that needs to flatten a multi-dimension list or tuple
into
> a single dimension list.
>
> [1, [2, 3], 4] => [1, 2, 3, 4]
>
> As part of the algorithm, I need to determine whether each object in the
> list is itself a sequence or whether it is an atom. Using the types
module
> would cause me to miss any sequence-like object that isn't actually the
> basic type. So, what's the best (easiest, most foolproof) way to
determine
> whether a Python object is a sequence?
>
> Thanks,
>
> Noel Rappin
>
>
> _________________________________________________________
> Do You Yahoo!?
> Get your free @yahoo.com address at http://mail.yahoo.com
>
>
More information about the Python-list
mailing list