Pythonic方式执行大型案例/开关

Aug*_*gan 2 python

我很确定这是Python中一个非常基本的概念,如果有人可以帮助我理解如何以pythonic/clean方式执行以下操作,我会很高兴.我真的很喜欢编码,所以我只是举个例子.我认为我要做的事情显而易见.

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]
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

And*_*Dog 11

为什么不这样做呢

item = list[int(thing) - 1]
Run Code Online (Sandbox Code Playgroud)

在更复杂的情况下,您应该使用字典映射输入到输出.


Ned*_*der 7

对于您要显示的特定代码,pythonic的事情是用以下内容替换整个if-ladder:

item = list[int(thing)-1]
Run Code Online (Sandbox Code Playgroud)

当然,你的真实代码可能不会像这样崩溃.

  • 这不仅仅是Pythonic,它是任何语言的好习惯. (2认同)