【问题标题】:Python multiple elif alternatives [duplicate]Python多个elif替代品[重复]
【发布时间】:2019-02-16 23:26:30
【问题描述】:

我有一个脚本需要遍历数千个不同但简单的选项。

我可以使用 if...elif 来遍历它们,但我想知道是否有比数千个 elif 更快/更好的选择。例如

if something == 'a':
    do_something_a
elif something == 'b':
    do_something_b
elif something == 'c':
    do_something_c
elif something == 'd':
    do_something_d
...
A thousand more elifs
...
else:
    do_something_else

我要做的事情通常是运行某种功能。

【问题讨论】:

  • 这取决于something 的来源。是某种用户输入吗?
  • 这将是一个变量值,通常取自我正在迭代的数据库中的列。
  • 你可以试试用字典...
  • 听起来你可以用字典来做到这一点

标签: python


【解决方案1】:

您可以通过这种方式使用字典:

def do_something_a():
    print 1

def do_something_b():
    print 2

dict = {'a': do_something_a, 'b': do_something_b}
dict.get(something)()

【讨论】:

  • 谢谢,我修复了; 我希望do_something_a() 函数已经存在。所以如果有东西== a,这段代码就会调用它
  • @melpomene 谢谢你向我展示了这一点。你是绝对正确的。我在答案中修复了它。
【解决方案2】:

我建议创建一个字典,将事物映射到它们各自的功能。然后你可以将这个字典应用到数据中。

更多信息:https://jaxenter.com/implement-switch-case-statement-python-138315.html (字典映射)

【讨论】:

    【解决方案3】:

    您可以使用字典来控制多个可能的逻辑路径:

    def follow_process_a():
       print('following a')
    
    def follow_process_b():
       print('following b')
    
    keyword_function_mapper = 
    {'a' : follow_process_a ,
     'b' : follow_process_b,                     
    }
    
    current_keyword = 'a'
    run_method = keyword_function_mapper[current_keyword]
    run_method()
    

    【讨论】:

    • 正是我需要的。谢谢!
    • 不客气!如果您愿意,也可以将此答案标记为已接受的答案(如果它是您正在寻找的答案)。
    猜你喜欢
    • 2016-05-30
    • 2012-12-16
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多