fast way to filter a set?

F

Fortepianissimo

I know I can do things like

s=Set(range(1,11))
s=Set(filter(lambda x:x%2==0,s))

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

Skip Montanaro

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
 
N

Nicola Mingotti

I know I can do things like

s=Set(range(1,11))
s=Set(filter(lambda x:x%2==0,s))

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

Can you ?
I tried python2.3 and 2.2 and it replies
: "NameError: name 'Set' is not defined" .

There is a PEP but it seems it's steel 'under consideration'.
http://www.python.org/peps/pep-0218.html

May be , if this proposal is accepted you
one day could write :
{ x for x in S if x%2 == 0 } # S be a set .

bye.
 
P

Peter Otten

Nicola said:
Can you ?
I tried python2.3 and 2.2 and it replies
: "NameError: name 'Set' is not defined" .

In 2.3 it works if you do

from sets import Set

first.

Peter
 
P

Peter Otten

Fortepianissimo said:
I know I can do things like

s=Set(range(1,11))
s=Set(filter(lambda x:x%2==0,s))

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

The Set constructor accepts any iterable, so you can do it all with
iterators instead of temporary lists:

from sets import Set
from itertools import ifilter

s = Set(range(1, 11))
print Set(ifilter(lambda x: x % 2 == 0, s))

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top