How to generically transform a list?
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Fri Aug 27 04:01:14 EDT 2004
Marco Aschwanden wrote:
>
> Thanks to all the hints which seem to prove that there is one and only
> one sensible approach - though some (like me) needed a few more lines.
>
> It is just funny how easy horizontal slicing is made (list[:]) but how
> "difficult" vertical slicing is. It is a common task and one does not
> realize how often one does need vertical slicing. eg.: getting the keys
> of dictionary is a vertical slicing, or turning a list into a dict
> involves vertical slicing...
>
> Just out of pure curiosity: Is there a langue that allows vertical and
> horizontal slicing and dicing with the same built-in pattern?
You can do it (sorta) in Python: use zip to turn the columns into rows
and vice-versa, apply the slicing, than zip back:
>>> l = [['a', 1, 11, 'aa'], ['b', 2, 22, 'bb'], ['c', 3, 33, 'cc']]
>>> zip(*(zip(*l)[2:0:-1]))
[(11, 1), (22, 2), (33, 3)]
Step-by-step to see what happens:
>>> zip(*l)
[('a', 'b', 'c'), (1, 2, 3), (11, 22, 33), ('aa', 'bb', 'cc')]
>>> zip(*l)[2:0:-1]
[(11, 22, 33), (1, 2, 3)]
>>> zip(*(zip(*l)[2:0:-1]))
[(11, 1), (22, 2), (33, 3)]
--
"Codito ergo sum"
Roel Schroeven
More information about the Python-list
mailing list