[Tutor] small problem with lists/tuples
Gregor Lingl
glingl at aon.at
Mon Sep 29 12:08:28 EDT 2003
Thomi Richards schrieb:
>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1
>
>
>Hi all,
>
>...
>
>['data']
>
>or:
>
>[['data']]
>
>or even:
>
>([['data']])
>
>what I'm trying to do, is "unpack" the duples, until i get to the actual data
>inside. Originally, i thought I could do it something like this:
>
>
>
Sometimes you will encounter the problem to get to the "actual data",
when they are packed in
some more complicated ("nested") lists or tuples, e.g.:
([1],[[2]],[[3,[[[4]]],[5]]]) ==> [1,2,3,4,5]
This can be accomplished by "flattening" these nested lists:
>>> def flatten(seq):
flat = []
for item in seq: # simple member
if not (isinstance(item,list) or isinstance(item,tuple)):
flat.append(item)
else: # sequence, so flatten this one too
flat.extend(flatten(item))
return flat # or if you want: return tuple(flat)
>>> flatten((1,(2,3)))
[1, 2, 3]
>>> flatten(([1],[[2]],[[3,[[[4]]],[5]]]))
[1, 2, 3, 4, 5]
>>> flatten([0,[1],[[2]],[[3,[([4],)],[5]]],("wow",)])
[0, 1, 2, 3, 4, 5, 'wow']
With flatten you can easily define a getdata like you need it:
>>> def getdata(data):
return flatten(data)[0]
>>> print data1, getdata(data1)
['data'] data
>>> print data2, getdata(data2)
[['data']] data
>>> print data3, getdata(data3)
([['data']],) data
>>> print data, getdata(data)
([['d']],) d
>>>
Regards, Gregor
More information about the Tutor
mailing list