fast way to filter a set?

Skip Montanaro skip at pobox.com
Wed Sep 17 12:24:07 EDT 2003


    fortepianissimo> I know I can do things like
    fortepianissimo> s=Set(range(1,11))
    fortepianissimo> s=Set(filter(lambda x:x%2==0,s))

    fortepianissimo> But this seems a bit slow since filter returns a list
    fortepianissimo> which then must be converted back to a set. Any tips?

The only thing which comes to mind is:

    >>> s = sets.Set(range(1,11))
    >>> s
    Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    >>> keys = list(s)
    >>> dummy = [s.discard(x) for x in keys if x%2]
    >>> s
    Set([2, 4, 6, 8, 10])

You still create a list, but don't create a second set.

Skip





More information about the Python-list mailing list