为迭代命令列表设置不同入口点的最佳方法是什么?

问题描述 投票:0回答:1

我有一个迭代 Python 命令列表:

def command_list(start_at):
    step1
    step2
    step3
    # ...
    stepN

现在我想要

start_at
此命令列表中的不同步骤,然后执行直到结束。似乎没有 goto 命令,而且 case 语句有一个隐含的中断,那么实现这个的最佳方法是什么?

python switch-statement iteration goto
1个回答
0
投票

有很多方法可以实现它,具体取决于命令的类型,

step
是:

  1. 如果步骤是函数,请将它们放入
    list
    中并迭代它们,如下所示:
def command_list(start_at):
    commands = [func1, func2, func3, func4, ...]
    for c in commands[start_at:]:
        c()

这可以像这样推广和改进:

def func_command_exec(command_l, start_at=1, arguments=()):
    """ Arguments shall be passed-in in the form:
    tuple[dict[str, dict|list], ...]
    
    Example:
    ({'kwargs':{'a':1, 'b':2}, 'posargs': [1, 2]}, ..)
    """
    # add some validation here
    if not isinstance(start_at, int) or not (0<start_at<len(command_l):
        # do some kind of action here, for example raise an exception or print something. I'm just going to return here.
        return 
    if len(arguments) != len(command_l):
        # do some kind of action here, for example raise an exception or print something. I'm just going to return here.
        return
    rets = []
    for i, a in zip(command_l[start_at:], arguments):
        k, p = a['kwargs'], a['posargs']
        retn = i(*p, **k)
        rets.append(retn)
    return rets

在上面的代码中,我添加了函数的

arguments
参数,以便您可以在许多不同的场景中通用地使用它。另外,我将函数列表作为参数传入,因此它不是固定值。在许多情况下,返回包含函数所有返回值的
list
也是一个非常方便的功能。

  1. 如果命令是语句,请将它们作为字符串放入
    list
    中,并迭代
    list
    ,使用内置函数
    exec()
    执行语句字符串,如下所示:
def command_list(start_at):
    commands = ['statement1', 'statement2', 'statement3', 'statement4'...]
    for c in commands[start_at:]:
        exec(c)

总而言之,虽然Python中没有

goto
,但有很多方法可以模仿它的行为。

© www.soinside.com 2019 - 2024. All rights reserved.