fast way to filter a set?

Skip Montanaro skip at pobox.com
Wed Sep 17 13:41:37 EDT 2003


    fortepianissimo> But this created two lists (keys and dummy)? Compared
    fortepianissimo> to the filter() method, which created a list and a new
    fortepianissimo> set, maybe your suggestion is still a bit faster...

You asked for alternatives.  I offered one.  I'll let you do the performance
testing. ;-)

Skip

    fortepianissimo> --- Skip Montanaro <skip at pobox.com> wrote:
    >> 
    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


    fortepianissimo> __________________________________
    fortepianissimo> Do you Yahoo!?
    fortepianissimo> Yahoo! SiteBuilder - Free, easy-to-use web site design software
    fortepianissimo> http://sitebuilder.yahoo.com





More information about the Python-list mailing list