tags:

views:

106

answers:

2

I'm pretty sure this is a really fundamental 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!

+7  A: 

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.

Ned Batchelder
That's not just Pythonic, it's good practice in any language.
David Zaslavsky
Oh yeah...that seems rather obvious in retrospect. Thanks!
August Flanagan
Daily WTF submission averted!
Nick Johnson
+9  A: 

Why not just do this

item = list[int(thing) - 1]

In more complex cases, you should use a dictionary mapping inputs to outputs.

AndiDog
+1 for suggesting dictionary mappings as an alternative to switch statements
ChristopheD