[Tutor] small problem with lists/tuples

Gregor Lingl glingl at aon.at
Mon Sep 29 11:46:24 EDT 2003



Thomi Richards schrieb:

>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1
>
>
>Hi all,
>
>Here's a small problem I'm trying to nut out:
>
Hello Thomi,
there are a few problems in your problem description:

>
>I have a function which returns some data in different forms. for example:
>
>sometimes, it will return:
>
>['data']
>
>or:
>
>[['data']]
>
>or even:
>
>([['data']])
>
do you mean a tuple with 1 element? Here:  ([['data']],)
(Otherwise [['data']] and ([['data']]) are the same thing - the latter one
beeing an expression, which is simly a list (which contains a list))

>
>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:
>
>while 1:
>	if (len(data) > 1):
>		data = data[0]
>	else:
>		break
>
>however, it turns out that the actual data itself could be a single character 
>long. 
>
If this is the case or not,  with your data your loop is always 
terminated during the first execution of
the loop body and doesn't change data at all. Or did you mean len(data) 
== 1 ?

>I guess I could use the type() builtin function, but I thought aybe 
>there was a cleaner/nicer way to do this? any ideas?
>  
>
Finally you have to decide, if you mind that the content of data will 
change.
Here an example solution (nothing special): a tiny function, which 
leaves data unchanged
and returns 'data' ... hmm (perhaps I should use different names...):

 >>> data1 = ["data"]
 >>> data2 = [["data"]]
 >>> data3 = ([["data"]],)
 >>> def getdata(data):
        while not isinstance(data,str):
                data = data[0]
        return data

 >>> print data3, getdata(data3)
([['data']],) data
 >>> print data1, getdata(data1)
['data'] data
 >>> print data2, getdata(data2)
[['data']] data
 >>> print data3, getdata(data3)
([['data']],) data
 >>> data = ([['d']],)
 >>> print data, getdata(data)
([['d']],) d
 >>>

Best wishes,
Gregor

>Thanks,
>
>- -- 
>Thomi Richards,
>http://once.sourceforge.net/
>
>
>-----BEGIN PGP SIGNATURE-----
>Version: GnuPG v1.2.3 (GNU/Linux)
>
>iD8DBQE/eAGh2tSuYV7JfuERAlrgAJ4vyXpBfC9JB1Irg9oY0xsMRJJsdwCfdSzA
>lqCwJ8+Puvrp9ZI6DkLAsY8=
>=iZ9d
>-----END PGP SIGNATURE-----
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>




More information about the Tutor mailing list