On 2 Dec 2005 17:08:02 -0800, [EMAIL PROTECTED] wrote:

>
>[EMAIL PROTECTED] wrote:
>> hello,
>>
>> i'm wondering how people from here handle this, as i often encounter
>> something like:
>>
>> acc = []    # accumulator ;)
>> for line in fileinput.input():
>>     if condition(line):
>>         if acc:    #1
>>             doSomething(acc)    #1
>>         acc = []
>>     else:
>>         acc.append(line)
>> if acc:    #2
>>     doSomething(acc)    #2
>>
>> BTW i am particularly annoyed by #1 and #2 as it is a reptition, and i
>> think it is quite error prone, how will you do it in a pythonic way ?
>>
It looks to me like itertools.groupby could get you close to what you want,
e.g., (untested)

    import itertools
    for condresult, acciter in itertools.groupby(fileinput.imput(), condition):
        if not condresult:
            dosomething(list(acciter)) # or dosomething(acciter) if iterator is 
usable

IOW, groupy collects contiguous lines for which condition evaluates to a 
distinct
value. Assuming this is a funtion that returns only two distinct values (for 
true
and false, like True and False), then if I understand your program's logic, you
do nothing with the line(s) that actually satisfy the condition, you just 
trigger
on them as delimiters and want to process the nonempty groups of the other 
lines,
so the "if not condresult:" should select those. Groupby won't return an empty 
group AFAIK,
so you don't need to test for that. Also, you won't need the list call in 
list(acciter)
if your dosomething can accept an iterator instead of a list.

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to