Reading 3 objects at a time from list

Peter Otten __peter__ at web.de
Sat Apr 11 12:14:48 CEST 2009


Matteo wrote:

> Hi all,
> let's see if there is a more "pythonic" way of doing what I'm trying
> to do.
> I have a lot of strings with numbers like this one:
> 
> string = "-1 1.3 100.136 1 2.6 100.726 1 3.9 101.464 -1 5.2 102.105"
> 
> I need to pass the numbers to a function, but three at a time, until
> the string ends. The strings are of variable length, but always a
> multiple of three.
> 
> That's what I did:
> num = string.split()
> for triple in zip(num[::3], num[1::3], num[2::3]):
>     func(*triple)
> 
> it works and I like slices, but I was wondering if there was another
> way of doing the same thing, maybe reading the numbers in groups of
> arbitrary length n...
> 
> any ideas?

Ideas? Many. But do they make sense?

>>> from itertools import *
>>> items = range(10)
>>> for chunk in iter((tuple(islice(items, 3)) for items in repeat(iter(items))).next, ()):
...     print chunk
...
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9,)

>>> for chunk in takewhile(bool, (tuple(islice(items, 3)) for items in repeat(iter(items)))):
...     print chunk
...
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9,)
>>> def make_read(items):
...     items = iter(items)
...     def read(n):
...             return tuple(islice(items, n))
...     return read
...
>>> from functools import partial
>>> for chunk in iter(partial(make_read(items), 3), ()):
...     print chunk
...
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9,)

>>> read = make_read(items)
>>> for n in [3,4,2,1]:
...     print read(n)
...
(0, 1, 2)
(3, 4, 5, 6)
(7, 8)
(9,)

>>> items = iter([3, "a", "b", "c", 2, "p", "q", 4, "x", "y", "z", "t"])
>>> read = make_read(items)
>>> for n in items:
...     print "".join(read(n))
...
abc
pq
xyzt




More information about the Python-list mailing list