Reading 3 objects at a time from list

Francesco Bochicchio bockman at virgilio.it
Sat Apr 11 05:48:36 EDT 2009


Chris Rebert ha scritto:
> On Sat, Apr 11, 2009 at 1:44 AM, Matteo <tadwelessar at gmail.com> 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...
> 
> See the grouper() recipe in the `itertools` module --
> http://docs.python.org/library/itertools.html
> 
> Cheers,
> Chris
> 


I would do that with a generator:

 >>> def groups(l,n) :
...   while l: yield l[:n]; l=l[n:]
...
 >>> list(groups(range(14),4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13]]
 >>> list(groups(range(18),3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17]]

Ciao
-----
FB







More information about the Python-list mailing list