a sequence question
Michael Hartl
mhartl at post.harvard.edu
Fri Jan 28 12:13:15 EST 2005
For problems like this I use a partition function defined in a utils.py
file that I use (based on Peter Norvig's utils file at
http://aima.cs.berkeley.edu/python/utils.py). Using partition, the
problem you posed can be solved by writing
#for a, b in partition([1, 2, 3, 4], 2):
# print a, b
The implementation of partition I use is simple-minded; the previous
posts in this thread suggest some more sophisticated ways to attack it
using generators.
#def partition(seq, partsize):
# """Partition a sequence into subsequences of length partsize."""
# ls = len(seq)
# assert ls % partsize == 0, ('length %s, partition size %s\n'
# % (ls, partsize))
# return [seq[i:(i+partsize)] for i in range(0, ls, partsize)]
Michael
More information about the Python-list
mailing list