Python style.

Richard Jones Richard.Jones at fulcrum.com.au
Wed May 10 18:07:41 EDT 2000


[Johann Hibschman]
> What you really want is something like:
> 
> for item1, item2 in transpose((list1, list2)):
> 
> to go from a tuple of two lists to a list of many tuples.  That's what
> that awful map None does.

   And, because I haven't had a chance to write any Python for far too long, 
here's an implementation of transpose() :)


Python 1.5.2 (#1, Apr 18 1999, 16:03:16)  [GCC pgcc-2.91.60 19981201 
(egcs-1.1.1  on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> class transpose:
...  def __init__(self, l1, l2):
...   self.l1, self.l2 = l1, l2
...  def __len__(self):
...   return min(len(self.l1), len(self.l2))
...  def __getitem__(self, i):
...   return self.l1[i], self.l2[i]
... 
>>> list1 = [1,2,3]
>>> list2 = ['a','b','c']
>>> for item1, item2 in transpose(list1, list2):
...  print item1, item2
... 
1 a
2 b
3 c
>>> 

   Note the slightly different syntax in the call to transpose(). Extending the 
transpose class to N lists and re-writing it in C is left as an exercise to the 
reader.


       Richard

ps. god-damn I have to get myself a job writing Python. Have to love a language 
that allows me to - in one shot - interactively crank up the interpreter, write 
a quick-n-dirty class I just thought up and test it out.






More information about the Python-list mailing list