Reputation: 401
Consider the following python class:
class Event(Document):
name = StringField()
time = DateField()
location = GeoPointField()
def __unicode__(self):
return self.name
Now I create a list of Events:
x = [Event(name='California Wine Mixer'),
Event(name='American Civil War'),
Event(name='Immaculate Conception')]
Now I want to add only unique events by searching via the event name. How is this done with the boolean in syntax?
The following is incorrect:
a = Event(name='California Wine Mixer')
if a.name in x(Event.name):
x.append(a)
Upvotes: 0
Views: 429
Reputation: 523614
By unique I think you want something like "if a.name not in x(Event.name):", which can be written as
if not any(y.name == a.name for y in x):
...
But if the name acts as an index, it is better to use a dictionary to avoid the O(N) searching time and the more complex interface.
event_list = [Event(name='California Wine Mixer'), ...]
event_dict = dict((b.name, b) for b in event_list)
# ignore event_list from now on.
....
a = Event(name='California Wine Mixer')
event_dict.setdefault(a.name, a)
Upvotes: 3