Selecting elements from a list

Michael Peuser mpeuser at web.de
Fri Sep 5 02:55:41 EDT 2003


"Martin Christensen" <knightsofspamalot-factotum at gvdnet.dk> schrieb im
Newsbeitrag news:87y8x4w6ym.fsf at gvdnet.dk...
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Howdy!
>
> Suppose I have a list A containing elements that I want to put into
> list B if they satisfy some property. The obvious way of doing it
> would be,
>
> B = []
> for i in A:
>     if A.property():
>        B.append(i)
>
> Now, list comprehensions, map() etc. can make a lot of list operations
> easier, but I haven't found a shorter, more elegant way of doing this.
> Have I missed something, or will I have to stick to my explicit loops?


from random import random
rowA1 =[random()]*100000; rowA2=[random()]*100000
rowB1 = rowA1[:]; rowB2 =rowA2[:]
rowC1 = rowA1[:]; rowC2 =rowA2[:]

def A(row1,row2):
    for x in row2:
        if x<0.5:
            row1.append(x)

def B(row1, row2):
    row1 += filter(lambda x: x<0.5,row2)

def C(row1, row2):
    row1 += [x for x in row2 if x<0.5]


def main():
    A(rowA1,rowA2)
    B(rowB1,rowB2)
    C(rowC1,rowC2)

profile.run("main()")
----------------
Kindly
Michael P






More information about the Python-list mailing list