Is there a better algorithm?
Fuzzyman
fuzzyman at gmail.com
Fri Jan 2 13:16:58 EST 2009
On Jan 2, 6:11 pm, Kottiyath <n.kottiy... at gmail.com> wrote:
> 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?
for i in l:
u = None
if len(i) == 2:
k, v = i
else:
k, u, v = i
Best I could come up with.
Alternatively:
def mangle(i):
if len(i) == 3:
return i
k, v = i
return k, None, v
for i in l:
k, u, v = mangle(i)
I'm sure there is a clever one liner using the Python 2.5 ternary
expression syntax. On the other hand I'm not sure it would be very
readable, so a straightforward (if less clever) solution is probably
better.
Michael
--
http://www.ironpythoninaction.com/
More information about the Python-list
mailing list