Message58716
| Author |
KirkMcDonald |
| Recipients |
KirkMcDonald |
| Date |
2007年12月18日.01:49:17 |
| SpamBayes Score |
0.0035587107 |
| Marked as misclassified |
No |
| Message-id |
<1197942559.18.0.611472238589.issue1643@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
One question which is asked with surprising frequency in #python is how
to yield multiple objects at a time from an iterable object. That is,
given [1, 2, 3, 4, 5, 6], get [(1, 2), (3, 4), (5, 6)].
The "grouper" function in the itertools recipes page provides one
pattern for this. A similar function (which behaves differently when the
length of the iterable is not evenly divisible by n) looks like this:
def group(iterable, n=2):
return itertools.izip(*(iter(iterable),)*n)
This code is fairly opaque to the novice. It is ugly, and takes a bit of
head-scratching to realize exactly what it is doing. Because this
operation is asked for with some frequency, and because this general
implementation is so ugly, I believe it belongs in the library.
There is a related function which is asked for much less frequently, but
which is a more general case of the group() function listed above. This
other function has a third "step" argument. This argument controls how
far each group is in advance of the previous group. For example:
list(group([1, 2, 3, 4], n=2, step=1)) -> [(1, 2), (2, 3), (3, 4)]
The original function is equivalent to this function when step is equal
to n.
Please find attached a patch with implementation, documentation, and tests. |
|
History
|
|---|
| Date |
User |
Action |
Args |
| 2007年12月18日 01:49:19 | KirkMcDonald | set | spambayes_score: 0.00355871 -> 0.0035587107 recipients:
+ KirkMcDonald |
| 2007年12月18日 01:49:19 | KirkMcDonald | set | spambayes_score: 0.00355871 -> 0.00355871 messageid: <1197942559.18.0.611472238589.issue1643@psf.upfronthosting.co.za> |
| 2007年12月18日 01:49:19 | KirkMcDonald | link | issue1643 messages |
| 2007年12月18日 01:49:18 | KirkMcDonald | create |
|