Hey all,
I just realized you can very easily implement a sequence grouping function
using Python 2.3's fancy slicing support:
def group(values, size):
return map(None, *[values[i::size] for i in range(size)])
[color=blue][color=green][color=darkred]
>>> group(range(20) , 4)[/color][/color][/color]
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15),
(16, 17, 18, 19)]
[color=blue][color=green][color=darkred]
>>> group(range(14) , 3)[/color][/color][/color]
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)]
I had to use map(None, *...) instead of zip(*...) to transpose the result
because zip throws away the "orphans" at the end. Anyway, this is a useful
function to have in your toolkit if you need to do pagination or
multi-column display, among other things...
Anyone have any other interesting applications of the extended slice syntax?
Peace,
Dave
--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
I just realized you can very easily implement a sequence grouping function
using Python 2.3's fancy slicing support:
def group(values, size):
return map(None, *[values[i::size] for i in range(size)])
[color=blue][color=green][color=darkred]
>>> group(range(20) , 4)[/color][/color][/color]
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15),
(16, 17, 18, 19)]
[color=blue][color=green][color=darkred]
>>> group(range(14) , 3)[/color][/color][/color]
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)]
I had to use map(None, *...) instead of zip(*...) to transpose the result
because zip throws away the "orphans" at the end. Anyway, this is a useful
function to have in your toolkit if you need to do pagination or
multi-column display, among other things...
Anyone have any other interesting applications of the extended slice syntax?
Peace,
Dave
--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Comment