How to iterate the input over a particular size?
Shawn Milochik
shawn at milochik.com
Sun Dec 27 10:14:01 EST 2009
A couple of notes:
Your code is too packed together. That makes it hard to read. Put in some whitespace (and comments, where necessary), and put spaces around your equal signs (x = 23 instead of x=23).
That said, here's something I threw together:
#!/usr/bin/env python
def chop_list(words, size = 9):
"""
Take a list, returning values
from the end of the list, and
the original list minus those values.
>>> chop_list(['test', 'with', 'four', 'words'], 2)
(['test', 'with'], ['four', 'words'])
>>> chop_list(['test', 'with', 'four', 'words'], 3)
(['test'], ['with', 'four', 'words'])
>>> chop_list(['test', 'with', 'four', 'words'], 4)
([], ['test', 'with', 'four', 'words'])
"""
chopped = words[-size:]
old_to_return = len(words) - len(chopped)
return words[:old_to_return], chopped
if __name__ == '__main__':
import doctest
doctest.testmod()
sample_string = '''There are more than nine words here.
I know because I wrote them.'''
word_list = sample_string.split()
while word_list:
word_list, new = chop_list(word_list)
print "Pulled off:\t%s\n\tRemaining: %s" % (new, word_list)
More information about the Python-list
mailing list