在Python中,在多种选择之间切换的正确方法是什么

2024-09-30 04:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python写一些类似人工智能的东西:

  1. 我的第一个代码是这样的:

    def run()
        if choice_a_is_avilable:
            choice_a()
            return
        elif choice_b_is_avilable:
            if choice_b_1_is_avilable:
                choice_b_1()
                return
            elif choice_b_2_is_avilable:
                choice_b_1()
                return
        else:
            choice_c()
    
    while 1:
        run()
    
  2. 但是决定选项是否可用的代码相当长,条件应该绑定到方法。我把代码改得更清楚了。你知道吗

    def run():
        if(choice_a()):
            return
        elif(choice_b()):
            return
        else(choice_c()):
            return
    
    def choice_b():
        if choice_b_is_avilable:
            if(choice_b_1()):
                return True
            elif(choice_b_2)
                return True
    
        return False
    
  3. 当越来越多的选择进入我的代码时,它变得越来越混乱和丑陋,我考虑使用Exception

    class GetChoiceException(Exception):
        """docstring for GetChoiceException"""
        def __init__(self, *args):
            super(GetChoiceException, self).__init__(*args)
    
    
    def run():
        try:
            choice_a()
            choice_b()
            choice_c()
        except GetChoiceException:
            pass
    
    def choice_a():
        if choice_a_is_avilable:
            some_function()
            raise GetChoiceException()
    

这是一种滥用Exception?你知道吗

在Python中进行选择的写入方式是什么?你知道吗


Tags: run代码selftruereturnifinitis
3条回答

如果choice_函数返回True如果成功,False如果不成功,则可以依次尝试每一个函数,直到其中一个函数成功,只需执行以下操作:

choice_a() or choice_b() or choice_c()

因为or是短路的,所以表达式一找到返回true的操作数就会结束。你知道吗

或者,如果它看起来更优雅,你可以这样写:

any(x() for x in (choice_a, choice_b, choice_c))

any也会短路,以便在找到真操作数时立即停止。你知道吗

这还允许您维护作为此操作一部分的函数选项列表,并按如下方式使用:

choices = [choice_a, choice_b, choice_c]
...
any(x() for x in choices)

如果这是您想要做的,那么您的异常方法中没有什么“错误”。不过,在我看来,它有点静态。你知道吗

不完全了解您的问题,一个可供考虑的选择是如果有帮助的话,提供一个可用函数调用的列表。您可以在列表中存储函数、类和几乎任何您想要的东西。然后您可以随机或选择一个并执行它。你知道吗

from random import choice

def foo():
    print "foo"

def bar():
    print "bar"

options = [foo,bar]
x = choice(options)
x()

将执行foo()或bar()。然后可以通过修改选项列表的内容来添加或删除函数。如果您只想执行列表中的第一个,您可以调用

options[0]()

希望这有帮助。你知道吗

汉努

这是否有效:

choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')

相关问题 更多 >

    热门问题