Is there a better algorithm?
Francesco Bochicchio
bockman at virgilio.it
Fri Jan 2 14:15:58 EST 2009
Kottiyath ha scritto:
> I have the following list of tuples:
> L = [(1, 2), (3, 4, 5), (6, 7)]
>
> I want to loop through the list and extract the values.
> The only algorithm I could think of is:
>>>> for i in l:
> ... u = None
> ... try:
> ... (k, v) = i
> ... except ValueError:
> ... (k, u, v) = i
> ... print k, u, v
> ---------
> 1 None 2
> 3 4 5
> 6 None 7
> -------------
> But, this algorithm doesnt look very beautiful - like say -> for k, u,
> v in L:
> Can anyone suggest a better algorithm to get the values?
One way to avoid explicit checks on tuple size (but making the code a
bit less clear and probably slower):
for i in l:
k, v, u = (i[:3]+(None,))[:3]
...
Ciao
-----
FB
More information about the Python-list
mailing list