Is there a better algorithm?

Hendrik van Rooyen mail at microcorp.co.za
Sat Jan 3 09:40:39 CET 2009


bearophile wrote:

>Fuzzyman:
>
>> for i in l:
>>  u = None
>>  if len(i) == 2:
>>   k, v = i
>>  else:
>>   k, u, v = i
>
>That's the best solution I have seen in this thread so far (but I
>suggest to improve indents and use better variable names). In
>programming it's generally better to follow the KISS principle.

Strange that nobody has suggested:

for Tup in Lst:
  for item in Tup:
    print item,
  print

Because if I recall correctly, all the OP was doing was printing the stuff.

Gets a bit hairier if you want to return the values though. - if you
replace the first print statement above with a yield and delete the
second, bare print, you lose knowledge of which tuple the item 
belongs to.

It is not trivial to do if you don't have a priori knowledge of
the maximum and minimum tuple length.

Seems to me it is one of those gems that is a PITA to do completely 
generally - basically because you don't know when you call it how
many items to unpack - so you have to return a count or something,
or just fall back on a two step approach - get the tuple from the list,
then do something with the items in the tuple.

- Hendrik





More information about the Python-list mailing list