[Tutor] Re: small problem with lists/tuples

pan at uchicago.edu pan at uchicago.edu
Mon Sep 29 16:05:47 EDT 2003


Thomi Richards wrote:

> I have a function which returns some data in different forms. for example:
> sometimes, it will return:
> 
> ['data']
> 
> or:
> 
> [['data']]
> 
> or even:
> 
> ([['data']])
> 
> what I'm trying to do, is "unpack" the duples, until i get to the actual data 
> inside. 



The following simple trick might work:

>>> a = ([['data']])
>>> a
[['data']]

>>> def unpack(target):
.. 	tmp = str(target)
.. 	tmp = tmp.replace('[','').replace(']','')
.. 	tmp = tmp.replace('(','').replace(')','')
.. 	return eval(tmp)
.. 
>>> unpack(a)
'data'

You can make the function a one-liner if you want:

>>> def unpack(target):
.. 	return eval(str(target).replace('[','').replace(']','').replace
('(','').replace(')',''))

>>> unpack(a)
'data'



pan



More information about the Tutor mailing list