New to Python idio开发者_如何学Cms and syntax. I have a Datastore StringListProperty that holds user keys. For most entities this property will have 0-10 keys, sometimes many more. I need to check the property for a key, most often there will be no match.
if entity.string_list.index(user_key) is not None:
# ....
This is throwing an error when there's no matching key. I can catch the exception, but I suspect I am not properly understanding how to check for matches in a List.
First off, if you're going to do a lot of searching you should use a set or a dictionary instead of a list unless you need to maintain order. Lookup on lists is O(n) and I know that tuples/dictionaries are much better. I believe constant time lookup.
Second, you're right about try/catch, you should use that if you expect that most of the time there WILL be a match.
Third, I think you're looking for,
if user_key in entity.string_list:
idx = entity.string_list.index(user_key)
EDIT: here are two links that shed some light on runtime guarantees. Very good stuff to know offhand when coding to keep your runtime down automatically
http://wiki.python.org/moin/TimeComplexity
http://bayes.colorado.edu/PythonIdioms.html
EDIT2: added method using dictionaries.
## pre-initialize a dictionary
lookupdict = dict((val, i) for i, val in enumerate(entity.string_list))
# loop over user_key
idx = lookupdict.get(user_key, None)
if idx is None:
continue
## do something with idx
>>> strings = ['abc', 'def', 'ghi']
>>> 'def' in strings
True
>>> 'foo' in strings
False
Does this work?
if user_key in entity.string_list:
# ...
精彩评论