Pythonic way to perform a large case/switch
I'm pretty sure this is a really fundame开发者_JS百科ntal concept in Python, I'd love it if someone could help me understand how to do the following in a pythonic/clean way. I'm really new to coding so I will just show an example. I think it will be obvious what I am trying to do.
for textLine in textLines:
foo = re.match('[1-100]', thing)
if foo:
list = db.GqlQuery("SELECT * FROM Bar").fetch(100)
if thing == '1':
item = list[0]
elif thing == '2':
item = list[1]
elif thing == '3':
item = list[2]
.
.
.
elif thing == '100':
item = list[99]
Thanks for the help!
Why not just do this
item = list[int(thing) - 1]
In more complex cases, you should use a dictionary mapping inputs to outputs.
For the specific code you're showing, the pythonic thing would be to replace the entire if-ladder with:
item = list[int(thing)-1]
Of course, it's possible that your real code doesn't lend itself to collapsing like this.
精彩评论