Python syntax in Lisp and Scheme

Bengt Richter bokr at oz.net
Tue Oct 7 10:49:55 EDT 2003


On Mon, 06 Oct 2003 11:59:22 -0700, David Eppstein <eppstein at ics.uci.edu> wrote:

>In article <blsbpf$i9n$1 at newsreader2.netcologne.de>,
> Pascal Costanza <costanza at web.de> wrote:
>
>> I don't know a lot about Python, so here is a question. Is something 
>> along the following lines possible in Python?
>> 
>> (with-collectors (collect-pos collect-neg)
>>    (do-file-lines (l some-file-name)
>>      (if (some-property l)
>>        (collect-pos l)
>>        (collect-neg l))))
>> 
>> 
>> I actually needed something like this in some of my code...
>
>Not using simple generators afaik.  The easiest way would probably be to 
>append into two lists:
>
>    collect_pos = []
>    collect_neg = []
>    for l in some_file_name:
>        if some_property(l):
>            collect_pos.append(l)
>        else:
>            collect_neg.append(l)
>
>If you needed to do this a lot of times you could encapsulate it into a 
>function of some sort:
>
>def posneg(filter,iter):
>    results = ([],[])
>    for x in iter:
>        results[not filter(x)].append(x)
>    return results
>
Um, about choosing names ...
 >>> filter
 <built-in function filter>
 >>> iter
 <built-in function iter>
;-)

>collect_pos,collect_neg = posneg(some_property, some_file_name)
>

Nah, just abuse a list comprehension:

 >>> seq = range(10)
 >>> test = lambda x: x%3==0
 >>> pos,neg = [(p,n) for p,n in[map(list,['']*2)]
 ...                  for q in [(x,test(x),i) for i,x in enumerate(seq)]
 ...                  if q[1] and p.append(q[0]) or not q[1] and n.append(q[0]) or not q[2]][0]
 >>> pos
 [0, 3, 6, 9]
 >>> neg
 [1, 2, 4, 5, 7, 8]

;-)

Regards,
Bengt Richter




More information about the Python-list mailing list